如何在.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 %>
答案 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