wilky
wilky

Reputation: 83

Ruby each do loop 'n' number of times

Hi I'm having trouble with the below loop in a .erb view

<% my_list.each do | list | %>
.. loop stuff.....
<% end %.

This works fine for looping through my list, but I only want to loop through the first 4 items in 'my_list' and not the whole list. I tried some things like:

<% my_list.each do | product |  3.times %>

but didn't seem to work as I think my ruby knowledge is limited to say the least!

Upvotes: 0

Views: 2095

Answers (4)

Mark Thomas
Mark Thomas

Reputation: 37507

It is apparent that you want to iterate through your list in groups of four (you really should amend your question, because this is an important piece of information). It is also apparent you are using Rails. Fortunately Rails has in_groups_of built into ActiveSupport:

<% my_list.in_groups_of(4) do |products| %>
  <% products.each do | product | %>

One advantage of this approach (over alternatives such as each_slice) is that in_groups_of will pad the end to make sure you always get four groups. It will pad with nil by default, but you can specify the padding yourself:

<% my_list.in_groups_of(4, "&nbsp;") do |products| %>

If you pass false as the pad, it will not pad at all and behaves just like each_slice.

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

Take first 4 element from my_list Array#first:

<% my_list.first(4).each do | product |  %>

use Array#each_slice for slice your array

<% my_list.each_slice(4) do | products |  %>
  <% products.each do | product |  %>

Upvotes: 2

Alok Anand
Alok Anand

Reputation: 3356

<% my_list[0..3].each do | list | %>

Upvotes: 0

Neil Slater
Neil Slater

Reputation: 27197

Use Array#take like this:

<% my_list.take(4).each do | product | %>

Upvotes: 5

Related Questions