Ruby on Rails 3.2.2,Ruby 1.9.3
我有来自Siz.requirements.all(模型)的数组数据 模型领域(siz,heigth,wigth,kol)
[{:siz=>10, :heigth = 30, :wigth = 20, :kol = 24},
{:siz=>10, :heigth = 30, :wigth = 10, :kol = 24},
{:siz=>10, :heigth = 30, :wigth = 20, :kol = 33},
{:siz=>10, :heigth = 20, :wigth = 20, :kol = 3},
{:siz=>10, :heigth = 20, :wigth = 20, :kol = 5},...
如何使用group by字段创建数组或散列 例如:
[{:siz=>10 => {:heigth=>"30" => {:wigth=>"20" => {:sum_kol => sum(kol)}}},
{:siz=>10 => {:heigth=>"30" => {:wigth=>"10" => {:sum_kol => sum(kol)}}},
{:siz=>10 => {:heigth=>"20" => {:wigth=>"20" => {:sum_kol => sum(kol)}}}]
答案 0 :(得分:5)
如果这是来自数据库,我会考虑使用数据库为您进行分组和汇总。但这是在Ruby中实现它的一种方法:
raw_data = [ {:siz=>10, :heigth => 30, :wigth =>20, :kol =>24},
{:siz=>10, :heigth =>30, :wigth =>10, :kol =>24},
{:siz=>10, :heigth =>30, :wigth =>20, :kol =>33},
{:siz=>10, :heigth =>20, :wigth =>20, :kol =>3},
{:siz=>10, :heigth =>20, :wigth =>20, :kol =>5} ]
# create a hash that defaults to three levels of nested hash values,
# with 0s at the leaves
summary = Hash.new do Hash.new do Hash.new do 0 end end end
# populate it
raw_data.each do |rec|
size, height, width, col = rec.values_at(:siz,:heigth,:wigth,:kol)
summary[size][height][width] += col
end
summary # => {10=>{30=>{20=>57, 10=>24}, 20=>{20=>8}}}
通常情况下,在Ruby中使用inject
/ reduce
而不是初始化+更新循环会更加惯用:
summary = raw_data.reduce(Hash.new do Hash.new do Hash.new do 0 end end end)
do |summary,rec|
size, height, width, col = rec.values_at(:siz,:heigth,:wigth,:kol)
summary[size][height][width] += col
summary
end
但是使用默认负载哈希并且需要在reduce块的末尾返回哈希,我认为原始版本在这里更清晰。