在EACH循环中查找当前索引(Ruby)

时间:2010-05-17 02:15:45

标签: ruby foreach

  

可能重复:
  Automatic counter in Ruby for each?

我想在每个循环中查找当前索引。我该怎么做?

X=[1,2,3]

X.each do |p|
 puts "current index..."
end 

2 个答案:

答案 0 :(得分:265)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

答案 1 :(得分:14)

x.each_with_index { |v, i| puts "current index...#{i}" }