0

I have a simple array of records from my database.

I'm building a responsive layout and I need to place only three items in each <div class="row"></div>.

How can I loop over the collection and take three items at a time to output one .row div, and each of the elements within?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
sergserg
  • 21,716
  • 41
  • 129
  • 182

1 Answers1

3

Something like this will work:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.each_slice(3) {|e| p "<div>#{e}</div>"}

See this question for more detail about each_slice: How to split (chunk) a Ruby array into parts of X elements?

An example:

<% for member_row in @members.each_slice(3).to_a %>
  <div class="row">

    <% for member in member_row %>

      <div class="col-md-4">
        <p><%= member.name %></p>
      </div>  

    <% end %>

  </div>
<% end %>
Community
  • 1
  • 1
Powers
  • 18,150
  • 10
  • 103
  • 108
  • Thanks! I'll edit your answer with a simple view example for completeness sake. – sergserg Feb 11 '14 at 23:14
  • 1
    @Serg don't use `for` in ruby, 99.9% of the case you don't need it, just do `@members.each_slice(3) do |member_row|` and `member_row.each do |member|` – bjhaid Feb 12 '14 at 02:08
  • 1
    @Serg, it's improper to add code to other people's answers. *IF* you have an example of what you did, you're free to append it to your question along with a little text explaining that's how you used it, but consider other people's answers sacred. Tweaking grammar and spelling, and even the formatting of code for readability, are acceptable. – the Tin Man Feb 12 '14 at 04:47
  • @theTinMan: Been using this site for years, first time I've heard of that silly rule. – sergserg Feb 12 '14 at 13:54
  • It's considered an inappropriate edit. If you did it with a lower rating the normal juried-review process would very likely have rejected it. – the Tin Man Feb 12 '14 at 14:42