Looping: break every x times

I have a bunch of pictures to display on a page and I want to do 4 per
row. This code works fine (inserting a
every 4th picture):

    <% i = 1 %>
    <% for photo in @photos do -%>
      <a href="/photos/show/<%=photo.id%>"><img

src="/photos/thumb/<%=photo.id%>"/>
<% if (i.modulo(4) == 0) %>


<% end %>
<% i = i+1%>
<% end %>

but I was wondering if there is a more elegant way to do this. Thanks.

That looks like eRb or Ruby on Rails or something but couldn’t you just
do:

<% @photos.each_with_index do |photo, i| %>

<% if (i % 4).zero? %>


<% end %>
<%end%>

To get each_with_index you must require ‘enumerator’ but you could do
Array#each_index and then instead of photo.id you have photos[i].id. Of
course, this all assumes that photos is an array.

Dan

Sounds like you’re looking for each_slice:

http://www.ruby-doc.org/core/classes/Enumerable.html#M003178

  • James M.

On Mon, 2006-12-18 at 02:04 +0900, Daniel F. wrote:

To get each_with_index you must require ‘enumerator’ but you could do
Array#each_index and then instead of photo.id you have photos[i].id.

You don’t need to require enumerator to get #each_with_index, at least
not in 1.8.5.

Cheers,
Daniel

Thanks Daniel, that’s what I was looking for.