合并两个哈希并在每个哈希中汇总嵌套哈希

时间:2014-07-18 17:32:31

标签: ruby hash

我有两个哈希:

g_record = {"4-2014"=>{:total_conversions=>0, :total_cost=>0.0}, "5-2014"=>{:total_conversions=>0, :total_cost=>189.8}, "6-2014"=>{:total_conversions=>0, :total_cost=>474.18}}

b_record = {"4-2014"=>{:total_conversions=>7, :total_cost=>639.7}, "5-2014"=>{:total_conversions=>5, :total_cost=>298.03}}

我想要的输出是:

combined_record = {"4-2014"=>{:total_conversions=>7, :total_cost=>639.7}, "5-2014"=>{:total_conversions=>5, :total_cost=>487.83}, "6-2014"=>{:total_conversions=>0, :total_cost=>474.18}}

我之前必须结合哈希值和求和值,并且一直尝试

的变体
g_record.merge(b_record) {|a, b, c| b + c}

但是这次我不明白我应该如何进入初始哈希来运行类似的东西。我觉得我应该能够做像

这样的事情
g_record.merge(b_record).each {|e| e.merge {|a, b, c| b + c}

但我知道这是不正确的。

1 个答案:

答案 0 :(得分:1)

我做:

merged_hash = g_record.merge(b_record) do |_, o, n|
  o.merge(n) { |_, o1, n1| o1 + n1 }
end

merged_hash 
# => {"4-2014"=>{:total_conversions=>7, :total_cost=>639.7},
#     "5-2014"=>{:total_conversions=>5, :total_cost=>487.83},
#     "6-2014"=>{:total_conversions=>0, :total_cost=>474.18}}