Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何对ActiveRecord对象数组进行分组?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如何对ActiveRecord对象数组进行分组?

Ruby on rails 如何对ActiveRecord对象数组进行分组?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个数组: <% @widgets.each do |w| %> ... <% end %> ... 如何将它们分组显示?让我们假设在4: <div>1, 2, 3, 4</div> <div>5, 6, 7, 8</div> etc. 1,2,3,4 5, 6, 7, 8 等 谢谢。试着使用每个片段(n): 需要“erb” @widgets=(1..8).到 template=对于您给出的特定示例,您需要:

我有一个数组:

<% @widgets.each do |w| %>
...
<% end %>

...
如何将它们分组显示?让我们假设在4:

<div>1, 2, 3, 4</div>
<div>5, 6, 7, 8</div>
etc.
1,2,3,4
5, 6, 7, 8
等

谢谢。

试着使用
每个片段(n)

需要“erb”
@widgets=(1..8).到

template=对于您给出的特定示例,您需要:


非常感谢。你们三分钟前都回复了。我不知道哪一个答案是有效的:(我会等着看谁是第一个。在所有条件相同的情况下,我总是把它给名声不那么好的人:)(而且,他的第一个答案比我的答案快52秒;悬停在“xx分钟前”以查看工具提示中的实际时间。)
require 'erb'

@widgets = (1..8).to_a

template = <<EOF
<% @widgets.each_slice(4) do |w| %>
  <div><%= w.join(', ') %></div>
<% end %>
EOF

puts ERB.new(template).result(binding)
# =>
  <div>1, 2, 3, 4</div>
  <div>5, 6, 7, 8</div>
<% @widgets.each_slice(4) do |ws| %>
  <div><%= ws.join(', ') %></div>
<% end %>
Person = Struct.new(:name,:age,:male) do
  def inspect
    "<#{'fe' unless male}male '#{name}' #{age}>"
  end
end

all = [
  Person.new("Diane",  12, false),
  Person.new("Harold", 28, true),
  Person.new("Gavin",  38, true),
  Person.new("Judy",   55, false),
  Person.new("Dirk",   59, true)
]

p all.group_by(&:male)
#=> {
#=>   false=>[ <female 'Diane' 12>, <female 'Judy' 55> ],
#=>   true =>[ <male 'Gavin' 38>, <male 'Harold' 28>,  <male 'Dirk' 59> ]
#=> }

p all.group_by{ |person| (person.age / 10) * 10 }
#=> {10=>[<female 'Diane' 12>],
#=>  20=>[<male 'Harold' 28>],
#=>  30=>[<male 'Gavin' 38>],
#=>  50=>[<female 'Judy' 55>, <male 'Dirk' 59>]}