简体   繁体   中英

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!

像这样使用Array#take

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

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM