2

Suppose the query customer_list = Customers.where ("state = ?", 'CA').order('first_name ASC') returns 30 customers, and the field .first_name has their first name.

I want to display their names in an html table with 3 more or less equal columns, eg, I want to fill the table as I go, wrapping to a new row each 3rd value.

Aaron    Amy    Andy
Arny     Beth   Bill
Bob      Carl   Charlie
etc etc

What is the 'ruby way' to flow the records into such a table's cells?

I could use .find_in_batches to grab 3 at a time, then iterate through the three for each column, but I suspect that's not the elegant ruby way.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jpw
  • 18,697
  • 25
  • 111
  • 187

2 Answers2

2

The each_slice helper method accepts a number n and then breaks the array into chunks of n, in this case 3.

<% @customer_list.each_slice(3) do |slice| -%>
 <tr>
  <% slice.each do |customer| -%>
    <td><%= customer.first_name %></td>
  <% end -%>
 <tr>
<% end -%>

See the documentations also check out this question.

Community
  • 1
  • 1
Alaa Othman
  • 1,109
  • 12
  • 16
  • 1
    This is VASTLY superior to using find_in_batches() because find_in_batches does NOT respect the order() whereas each_slice() does respect the order(). – jpw Oct 16 '14 at 07:41
-1

You could always do a simple:

<tr>
<%
i=1
customer_list.each do |customer|
if(i%3==0) then 
i=1%>
</tr><tr>
<%
end
%>
<td><%=customer.first_name%></td>
<%
i+=1
end
%>
</tr>

I'm not sure if there's a "Ruby way of doing it", though I'm by no means an expert.

Myxoh
  • 93
  • 9