215

So I have this loop:

<% @images.each do |page| %>

<% end %>

How would I get the index of "page" inside of the loop?

2
  • 17
    For the info of others looking at this, all the answers supplied are applicable to Ruby in general, not specific to Rails functionality.
    – Phrogz
    Commented Jan 27, 2011 at 2:29
  • Just loop through each_with_index and you are good to go!
    – Ravindra
    Commented Dec 13, 2016 at 11:37

3 Answers 3

404
<% @images.each_with_index do |page, index| %>

<% end %>
1
  • 1
    Didn't work for me. Had to use the each_with_index method as the other answers suggest. Commented Mar 4, 2019 at 21:58
53

The two answers are good. And I also suggest you a similar method:

<% @images.each.with_index do |page, index| %>
<% end %>

You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index see how it's .each and then .with_index.

2
  • This method newer and allows you to offset the index (say you wanted to start the loop on item 1 instead of 0 or something like that) Commented Jun 9, 2015 at 23:16
  • 2
    It took me a while to realise this code wasn't identical to the accepted answer!
    – mwfearnley
    Commented Nov 28, 2016 at 12:50
16

Try each_with_index.

Not the answer you're looking for? Browse other questions tagged or ask your own question.