215

So I have this loop:

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

<% end %>

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

criticerz
  • 3,397
  • 3
  • 23
  • 24
  • 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 Jan 27 '11 at 02:29
  • Just loop through each_with_index and you are good to go! – Ravindra Dec 13 '16 at 11:37

3 Answers3

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

<% end %>
PreciousBodilyFluids
  • 11,881
  • 3
  • 37
  • 44
51

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.

Sgnl
  • 1,808
  • 22
  • 30
Tatsuro Baba
  • 592
  • 3
  • 5
16

Try each_with_index.

Brett Bender
  • 19,388
  • 2
  • 38
  • 46