Finding out current index in EACH loop (Ruby)

RubyForeach

Ruby Problem Overview


> 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 

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmeowView Question on Stackoverflow
Solution 1 - RubyChubasView Answer on Stackoverflow
Solution 2 - RubyhorseyguyView Answer on Stackoverflow