Going through an array in batches

Hi,

Im looking to display my products in a table so that they show up as:

X-X-X-X
X-X-X-X
X-X-X…

I have my @products but how can I loop it so that for every 4 (or N)
products I can insert a new

to close the previous and open a
new row?

On 10/16/06, Shai S. [email protected] wrote:

I have my @products but how can I loop it so that for every 4 (or N)
products I can insert a new to close the previous and open a
new row?

#in_groups_of

<% @products.in_groups_of(4) do |row| %>

<% row.each do |product| %> <%= product.name %> <% end %> <% end -%>

Matt

Matt Pelletier wrote:

#in_groups_of

Ruby on Rails — New in Rails: Enumerable#group_by and Array#in_groups_of

<% @products.in_groups_of(4) do |row| %>

<% row.each do |product| %> <%= product.name %> <% end %> <% end -%>

So simple! I should have guessed. Thank you.

Hi –

On Mon, 16 Oct 2006, Matt Pelletier wrote:

<% row.each do |product| %> <%= product.name %> <% end %> <% end -%>

This brings back memories: Array#in_chunks_of was one of the first
add-on methods I ever wrote :slight_smile: There’s also now this in Ruby:

require ‘enumerator’
array.each_slice(n) do |slice| … end

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org