如何获得一个3“每个”循环的轨道计数器?

时间:2011-12-01 13:26:29

标签: ruby-on-rails ruby ruby-on-rails-3

如何在.each循环中添加计数器?这样做有简单的方法吗? 我尝试了以下但它似乎不起作用。谢谢!

<% @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 %>

2 个答案:

答案 0 :(得分:40)

使用each_with_index:索引将自动成为您的计数器(但请注意它从0开始而不是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 %>

答案 1 :(得分:3)

看看Enumerable#each_with_index

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