How to do this?

Hi,
I’d like iterate through a model object(its an array object as you know)
in the view so that it displays 2 database table rows in one html table
row(in separate columns

) and then moves to display the next 2
database table rows in the next html table row.

Like this:

array[0] array[1]
array[2] array[3]

Im kinda clueless about this. Any ideas?
Thanks

Petr

Thanks.

But, you forgot to mention how to bring that into html, so if you could
do that it would be great.

Thanks again,
Petr

Max M. wrote:

On 10/17/06, Petr [email protected] wrote:

Im kinda clueless about this. Any ideas?
Thanks

Petr

Either the rails only way:

some_array.in_groups_of(2)

which pads with nil, or the more ruby way:

require ‘enumerator’

some_array.slice(2)

Cheers,
Max

On 10/17/06, Petr [email protected] wrote:

Im kinda clueless about this. Any ideas?
Thanks

Petr

Either the rails only way:

some_array.in_groups_of(2)

which pads with nil, or the more ruby way:

require ‘enumerator’

some_array.slice(2)

Cheers,
Max

I asked this yesterday in a post titled “Going through an array in
batches…”

Hope this helps:

#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 -%>

On 10/18/06, Petr [email protected] wrote:

Thanks.

But, you forgot to mention how to bring that into html, so if you could
do that it would be great.

Thanks again,
Petr

Use in place of some_list.each. Instead of

<% for thing in list %>
… render stuff …
<% end %>

use

<% list.in_groups_of(2) do |two_things| %>

<%= two_things[0].some_attribute if two_things[0] %> <%= two_things[1].some_attribute if two_things[1] %> <% end %>

The nil check is necessary, as in_groups_of pads the last “row” with
nils if there are not enough elements in the list.

BTW, googling for “rails in_groups_of” would have gotten you there as
well…

Cheers,
Max

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