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

http://weblog.rubyonrails.org/2006/3/1/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 -%>

Matt

Matt Pelletier wrote:

#in_groups_of

http://weblog.rubyonrails.org/2006/3/1/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] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs