ruby中迭代器的索引计数方法?

yll*_*ate 10 ruby

移动迭代时,例如:

array.each do |row|
  puts "Current row count: " + row.current_row_index
  # do some more stuff
end
Run Code Online (Sandbox Code Playgroud)

有没有办法获取当前迭代/行的索引?显然我可以扔进一个计数器,但我很好奇是否有一个索引函数的快捷方式,显示它的当前位置.

一直在挖掘可用的方法pry,但是我没有看到任何看似开箱即用的东西.

Dav*_*son 27

array.each_with_index |row, index|
  puts index
end
Run Code Online (Sandbox Code Playgroud)


meg*_*gas 6

如果你需要完全索引

array.each_index do |index|
  puts index
end
Run Code Online (Sandbox Code Playgroud)