user3591126
user3591126

Reputation: 211

Ruby On Rails each method

Say I want to call .each on @users and in my erb I have:

<% @user.each do |user| %>
<p><%= user.name %></p>
<% end %>

Simple enough. But after every 5th user I need to add a clearfix of this:

<div class="clearfix visible-xs"></div>

What is the best way to go about this?

Upvotes: 2

Views: 180

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Maybe .each_slice will be another way to provide this functionality:

<% @users.each_slice(5) do |users| %>
   <% users.each do |user| %>
      <p><%= user.name %></p>
   <% end %>
   <div class="clearfix visible-xs"></div>
<% end %>

Upvotes: 5

Marek Lipka
Marek Lipka

Reputation: 51151

Enumerable#each_with_index should be ok:

<% @users.each_with_index do |user, index| %>
  <p><%= user.name %></p>
  <% if (index + 1) % 5 == 0 %>
    <div class="clearfix visible-xs"></div>
  <% end %>
<% end %>

Upvotes: 6

Related Questions