如何分组ActiveRecord对象数组?

时间:2022-08-08 13:18:41

I have an array:

我有一个数组:

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

How can I display them in groups? Let's say by 4:

如何在群组中显示它们?让我们说4:

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

Thank you.

2 个解决方案

#1


1  

Try to use each_slice(n):

尝试使用each_slice(n):

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>

#2


2  

For the specific example you gave, you want each_slice:

对于您提供的具体示例,您需要each_slice:

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

You might also be interested in each_cons (each consecutive, e.g. "1,2,3", "2,3,4", "3,4,5", etc.) or group_by for arbitrary groupings.

对于任意分组,您可能也对each_cons(每个连续,例如“1,2,3”,“2,3,4”,“3,4,5”等)或group_by感兴趣。

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>]}

#1


1  

Try to use each_slice(n):

尝试使用each_slice(n):

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>

#2


2  

For the specific example you gave, you want each_slice:

对于您提供的具体示例,您需要each_slice:

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

You might also be interested in each_cons (each consecutive, e.g. "1,2,3", "2,3,4", "3,4,5", etc.) or group_by for arbitrary groupings.

对于任意分组,您可能也对each_cons(每个连续,例如“1,2,3”,“2,3,4”,“3,4,5”等)或group_by感兴趣。

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>]}