Wednesday, September 3, 2008

Method of the Day: Array#in_groups_of

This one is great for building rows of tables.
<table>
<% @models.in_groups_of(3).each do |row| %>
  <tr>
    <% row.each do |model| %>
      <td><%= model.to_s %></td>
    <% end %>
  </tr>
<% end %>
</table>

This will render the array in a left-to-right, top-down order. If you want to render in top-down, left-to-right order, try this:
  <% num_cols = 3 %>
  <% @models.in_groups_of((@models.length/num_cols).ceil).transpose.each do |row| %>
  ...
  
That should give you the (more common) column-first layout.

1 comment:

Marcin Domanski said...

Turns out there is a method for that already - it's in_groups ;-)

Check it out, it gives you vertical groups, or columns if you like. One problem though. It doesn't generate columns like in a phone book. Instead, they seem to be balanced and have similar number of elements. Not quite what you would expect I think.