DDDD
DDDD

Reputation: 3940

Ruby loop with an interval

My loop is creating a new row for each iteration. I want it to loop 3 times per row.

I havent had any luck with 3.times {...} or .step(3).

My loop:

<% @image_paths.each do |image| %>
<div class="row">
<ul class="thumbnails">
        <li class="span3">
            <h3><%= File.basename(image) %></h3>
            <% image_path = ["", File.dirname(image).split("public"),"/", File.basename(image)].join('') %>
        <%= link_to image_tag(image_path), image_path[/\/.*/]%>
    </li>
 </ul>
</div>
<% end %>

Upvotes: 1

Views: 301

Answers (2)

Kirti Thorat
Kirti Thorat

Reputation: 53048

With Rails, you can use in_groups_of method to get a group of 3 image_path's,

<% @image_paths.in_groups_of(3, false).each do |images| %>
<div class="row">
<% images.each do |image| %>
  <ul class="thumbnails">
          <li class="span3">
              <h3><%= File.basename(image) %></h3>
              <% image_path = ["", File.dirname(image).split("public"),"/", File.basename(image)].join('') %>
          <%= link_to image_tag(image_path), image_path[/\/.*/]%>
      </li>
   </ul>
 <% end %>
</div>
<% end %>

Refer to Official Documentation of Rails for details.

Upvotes: 0

Alex Mcp
Alex Mcp

Reputation: 19315

You're looking for

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice

<% @image_paths.each_slice(3) do |slice| %>
  <div class="row">
    <ul class="thumbnails">
      <% slice.each do |image| %>
        <li class="span3">
          <h3><%= File.basename(image) %></h3>
          <% image_path = ["", File.dirname(image).split("public"),"/", File.basename(image)].join('') %>
          <%= link_to image_tag(image_path), image_path[/\/.*/]%>
        </li>
      <% end %>
    </ul>
  </div>
<% end %>

So the slice variable will be an array of 3 (or 2 or 1) images, or whatever was in the initial collection. Hope that helps!

Upvotes: 2

Related Questions