Rails get index of "each" loop

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


So I have this loop:

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

<% end %>

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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

<% end %>

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

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
QuestioncriticerzView Question on Stackoverflow
Solution 1 - Ruby on-RailsPreciousBodilyFluidsView Answer on Stackoverflow
Solution 2 - Ruby on-RailsTatsuro BabaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsBrett BenderView Answer on Stackoverflow