简体   繁体   English

Ruby每个循环执行'n'次

[英]Ruby each do loop 'n' number of times

Hi I'm having trouble with the below loop in a .erb view 嗨,我在.erb视图中遇到以下循环问题

<% 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. 这对于循环浏览我的列表很好,但是我只想循环浏览“ my_list”中的前4个项目,而不是整个列表。 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 Array#first中获取前4个元素:

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

use Array#each_slice for slice your array 使用Array#each_slice切片数组

<% 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. 很明显,您正在使用Rails。 Fortunately Rails has in_groups_of built into ActiveSupport: 幸运的是,Rails的in_groups_of已内置到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. 这种方法的优势(相对于诸如each_slice替代方法)是in_groups_of将填充末尾以确保您始终获得四个组。 It will pad with nil by default, but you can specify the padding yourself: 默认情况下,它将填充为nil ,但是您可以自己指定填充:

<% 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 . 如果将false用作填充,它将完全不填充,其行为类似于each_slice

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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