0

Let say i have the following car loop and i want to display 4 cars on one row and then create a new row etc.

<table>
    <tr>
    <% @cars.each do |car| %>
        <td><%= car.name %></td>
    <% end %>
    </tr>
</table>

So i looks like this:

car1 car2 car3 car4

car5 car6 car7 car8

car9 car10 ... ... ...

How do I do that?

2 Answers 2

2
<table>
  <% @cars.each_slice(4) do |cars| %>
    <tr>
      <% cars.each do |car| %>
        <td><%= car.name %></td>
      <% end %>
    </tr>
  <% end %>
</table>

Adding a class to last td in a row:

<table>
  <% @cars.each_slice(4) do |cars| %>
    <tr>
      <% cars.each do |car| %>
        <td <%= "class='my_class'" if car == cars.last %>>
          <%= car.name %>
        </td>
      <% end %>
    </tr>
  <% end %>
</table>
Sign up to request clarification or add additional context in comments.

1 Comment

Great! What if I want to add a class to the last TD before another row is added?
1

You can take advantage of the each_slice method from Enumerable, an example like so:

[1,2,3,4,5,6,7,8,9,10].each_slice(4).to_a
#=> [1, 2, 3, 4], [5, 6, 7, 8], [9, 10]] 

So your code would be like:

<table>
  <% @cars.each_slice(4) do |cars| %>
    <tr>
      <% cars.each do |c| %>
        <td><%= c.name %></td>
      <% end %>
    </tr>
  <% end %>
</table>

Point is, always check out the Enumerable page for things like this. Ruby provides amazing methods like this!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.