0

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!

4 Answers 4

5

Use Array#take like this:

<% my_list.take(4).each do | product | %>
Sign up to request clarification or add additional context in comments.

1 Comment

great , worked thanks, AS an aside, how would I then loop through the next group of items something like take (4+1)
2

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 |  %>

1 Comment

thanks, how would I then loop from Number 5 in the list
2

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.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.