0

Ruby on Rails 3.2.2、Ruby 1.9.3

我有来自 Siz.requirements.all (model) 模型字段 (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)}}}]
4

1 回答 1

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

inject通常在 Ruby 中使用/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 块末尾返回散列的需要,我认为原始版本在这里更干净。

于 2012-04-26T16:48:06.007 回答