1

This is my code:

<table class="video_table">
  <% count = 0 %>
  <tr>
  <% @f_videos.each do |f_video| %>
     <td><%= f_video.name %></td>
     <td><%= f_video.date_added %></td>
     <td><%= f_video.views %></td>
     <% count +=1 %>
     <% if count == 4 %>
         </tr>
     <% end %>
  <% end %>
</table>

at each 4 videos placed I want the table to switch row. So I implemented a counter. But it is not working. Any ideas?

2
  • 2
    Well, it'll only equal 4 once, since you don't reset it. Generally this type of task is done with the % (modulo) operator so it doesn't have to be reset. Commented Dec 10, 2011 at 17:29
  • Please indent your code properly, and please don't use "thx". Commented Dec 11, 2011 at 22:24

2 Answers 2

2

Your count will only be set to 4 once.

Instead of if count == 4 use if count % 4 == 0

This will repeat the </tr> for each multiple of 4


Alternatively, you could skip using the count variable and use each_with_index to get the same result

<table class="video_table">
<% @f_videos.each_with_index do |f_video, i| %>
  <tr>
    <td><%= f_video.name %></td>
    <td><%= f_video.date_added %></td>
    <td><%= f_video.views %></td>
    <% if (i+1) % 4 == 0 %>
      </tr>
    <% end %>
<% end %>
</table>

Even better! each_slice

<table class="video_table">
<% @f_videos.each_slice(4).to_a do |slice| %>
  <tr>
    <% slice.each do |f_video| %>
      <td><%= f_video.name %></td>
      <td><%= f_video.date_added %></td>
      <td><%= f_video.views %></td>
    <% end %>
  </tr>
<% end %>
</table>
Sign up to request clarification or add additional context in comments.

3 Comments

thx! my code had also another error, <tr> should be above <% @f_videos.each do |f_video| %>
@TestTest see the each_slice example; I think this the best way to do this.
Also, welcome to StackOverflow! If this answer worked for you, please mark it as accepted :)
1

Another solution:

<table class="video_table">
<% @f_videos.in_groups_of(4) do |group| %>
  <tr>
    <% group.each do |f_video| %>
      <td><%= f_video.name %></td>
      <td><%= f_video.date_added %></td>
      <td><%= f_video.views %></td>
    <% end %>
  </tr>
<% end %>
</table>

in_groups_of has the added value/advantage that, when needed, it allows for padding any remaining slots with eg '&nbsp;', which can be very useful. See the docs.

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.