33

I have X number of image objects that I need to loop through in a view and want to create a new div every 6 objects or so (for a gallery).

I have looked at cycle but it seems to change every other record. Does anyone know of a way to insert code into a view every 6 times?

I could probably do it with nested loops but I am kinda stumped on this one.

2 Answers 2

108

You can use Enumerable#each_slice in conjunction with #each to avoid inline calculations. each_slice breaks the array into chunks of n, in this case 6.

<% @images.each_slice(6) do |slice| -%>
  <div class="gallery">
    <% slice.each do |image| -%>
      <%= image_tag(image.url, :alt => image.alt) %>
    <% end -%>
  </div>
<% end -%>
8
  • That seems like a more conventional way to do it.. I'll give a a try.
    – Dustin M.
    May 17, 2010 at 19:29
  • Thanks Thorn, I prefer this method to keep my views clean. Thanks!
    – Dustin M.
    May 17, 2010 at 19:34
  • 1
    Thanks, this works great. A lot more sexy than keeping a counter.
    – Mosselman
    Dec 20, 2012 at 16:53
  • How would you handle this when using an interator that doesn't support this thing like @documents.each_hit_with_result in Solr?
    – tibbon
    Jan 10, 2013 at 17:20
  • I haven't used Solr before, but I see that method returns an enumerable if no block is given (typical Ruby behavior). In that case, you should be able to just chain on top of it: @documents.each_hit_with_result.each_slice(6) do |slice|. Source: github.com/sunspot/sunspot/blob/master/sunspot/lib/sunspot/…
    – thorncp
    Jan 14, 2013 at 20:21
14

This is a Ruby question. You can meld this into whatever your view is trying to do.

@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Poop out the div
  end
  # Do whatever needs to be done on each iteration here.
end
1
  • Great solution @jdl, this works perfect for injecting an ad partial into a looped list (which I had trouble figuring out in the past). Oct 3, 2018 at 1:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.