Help with identifying every nth item in a do loop

I have the following loop
I am trying to identify every 3rd item in loop so that I can create a layout row (to prevent different heights of divs causing weird flow in the page). I am using dato middleman gem but i think that is irrelevant as this is purely ruby syntax issue??

<% dato.home.types_of_paddling.each do |typesofpaddling, i| %>
<% puts '<div class="row">' if (i % 3 == 0) %>
 Block Content Here
<% puts '</div>' if (i % 3 == 2) %>
<% end %>

I get an error as follows undefined method `%’ for nil:NilClass

Use each_with_index do |types, index|

1 Like

@tomrutgers

I need to explain a bit more maybe, I need to pull out every item in loop but be able to identify every 3rd one, so each_with_index only gets me every 3rd one!

Is it not possible to use conditional inside an each.do loop?

The only difference between each and each_with_index is that… well… the latter returns an actual index. The identification of the third item is up to your logic. For class based stuff:

<% dato.home.types_of_paddling.each_with_index do |typesofpaddling, i| %>
  <div class="#{'row' if (i % 3 == 0)}">
    ...
  </div>
<% end %>

If you need different content you can do something like:

<% dato.home.types_of_paddling.each_with_index do |typesofpaddling, i| %>
  <% if (i % 3 == 0) %>
    ...
  <% else %>
    ... 
  <% end %>
<% end %>

@tomrutgers Nailed it again Tom, much obliged!

1 Like