Loop each x elements
What is the best way to show a list with 20 images 开发者_如何学JAVAin rows of 5? Or, in other words, how do I clean up this ugly snippet?
<div class="row">
<% @images.each_with_index do |image, index| %>
<% if index != 0 && index % 5 == 0 %>
</div><div class="row">
<% end %>
<%= image_tag image.url %>
<% end %>
</div>
You can use each_slice to loop through the images in rows of five images each:
<% @images.each_slice(5) do |row| %>
<div class="row">
<% row.each do |image| %>
<%= image_tag image.url %>
<% end %>
</div>
<% end %>
you can also use in_groups_of
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Grouping.html which also has other options.
精彩评论