【问题标题】:How to get index of value in anonymous array inside of iteration如何在迭代内获取匿名数组中的值索引
【发布时间】:2014-10-28 06:26:32
【问题描述】:

我希望能够获取一个匿名数组,遍历它并在迭代器块内部找出当前元素的索引。

例如,我试图只输出每三个元素。

["foo", "bar", "baz", "bang", "bamph", "foobar", "Hello, Sailor!"].each do |elem|
  if index_of(elem) % 3 == 0 then
    puts elem
  end
end 

(其中index_of 是一个不存在的方法,在这里用作占位符来演示我正在尝试做的事情)

理论上输出应该是:

foo bang Hello, Sailor!

当我命名数组时,这非常简单。但是当它是匿名的时,我不能很好地按名称引用数组。我尝试过使用self.find_index(elem)self.index(elem),但都失败并出现错误:NoMethodError: undefined method '(find_)index' for main:Object

这样做的正确方法是什么?

【问题讨论】:

  • 只使用索引,a = [ "a", "b", "c" ] a.index("b") 返回1
  • 这当然是真的,但是我的问题是询问如何在 anonymous 数组的上下文中执行此操作。我不能说 a.index(...) 因为没有变量 a 数组绑定到。

标签: ruby arrays indexing iteration


【解决方案1】:

另一种方式:

arr = ["foo", "bar", "baz", "bang", "bamph", "foobar", "Hello, Sailor!"]

arr.each_slice(3) { |a| puts a.first }
  #=> foo
  #   bang
  #   Hello, Sailor!

【讨论】:

    【解决方案2】:

    使用each_with_index:

    arr = ["foo", "bar", "baz", "bang", "bamph", "foobar", "Hello, Sailor!"]
    
    arr.each_with_index do |elem, index|
      puts elem if index % 3 == 0
    end 
    

    【讨论】:

    • 请看我上面对 Sam D 的评论。
    • @alex0112 我没有引用块内的数组
    • @alex0112 只需将arr 替换为数组字面量即可。
    • 只要计时器用完,我就会接受你的回答@Stefan。
    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多