142

Possible Duplicate:
Automatic counter in Ruby for each?

I want to find out the current index while i am in the each loop. how do i do so?

X=[1,2,3]

X.each do |p|
 puts "current index..."
end 
Community
  • 1
  • 1
meow
  • 27,476
  • 33
  • 116
  • 177

2 Answers2

330
X.each_with_index do |item, index|
  puts "current_index: #{index}"
end
Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
Chubas
  • 17,823
  • 4
  • 48
  • 48
18

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

horseyguy
  • 29,455
  • 20
  • 103
  • 145