Francois
Francois

Reputation: 10631

How do I get a counter for an "each" loop in Rails?

How do I add a counter to an .each loop? Is there any easy way of doing this? I tried the below, but it does not seem to work.

<% @album.each do |e| %>
   <%= e %> #my_counter_does_not_work :)
   <%= link_to e.name, :controller => "images", :action => "album", :album_id => e.id, :album_name => e.name %>
<% end %>

Upvotes: 14

Views: 17589

Answers (2)

David Sulc
David Sulc

Reputation: 25994

Use each_with_index : the index will automatically be your counter (but note it starts at 0 and not 1):

<% @album.each_with_index do |e, index| %>
  <%= link_to e.name, :controller => "images", :action => "album", :album_id => e.id, :album_name => e.name %>
<% end %>

Upvotes: 46

Nerian
Nerian

Reputation: 16177

Take a look at Enumerable#each_with_index

http://apidock.com/ruby/Enumerable/each_with_index

Upvotes: 3

Related Questions