如何在Ruby中合并和求和嵌套哈希

时间:2015-12-08 17:15:10

标签: ruby hash merge

我有几个哈希对象,如下所示。

stats3 = {
  "Test1" => {
     "Variant A" => 11,
     "Variant B" => 22
  },
  "Test2" => {
     "Variant C" => 33,
     "Variant D" => 44
  }
}

我想要一个函数,它将任意数量的类似结构的哈希对象作为输入,并返回一个对值进行求和的结果。

username hostname=(as user name) command

它们保证具有相同的键,但对于整数具有不同的值。我想将这些键合并到具有所有相同键的一个对象中,并且值是所有数字的总和。我不确定最好的办法是什么。

编辑:如果可能,我想要一个通用的答案,这意味着该解决方案适用于任意数量的嵌套级别。

1 个答案:

答案 0 :(得分:1)

你的问题并不完全清楚,但我认为你想要这样的事情:

stats1 = {
  "Test1" => { "Variant A" => 34, "Variant B" => 64 },
  "Test2" => { "Variant C" => 23, "Variant D" => 314 }
}

stats2 = {
  "Test1" => { "Variant A" => 100, "Variant B" => 200 },
  "Test2" => { "Variant C" => 300, "Variant D" => 400 }
}

stats3 = {
  "Test1" => { "Variant A" => 1000, "Variant B" => 2000 },
  "Test2" => { "Variant C" => 3000, "Variant D" => 4000 }
}

def sum_stats(*hashes)
  hashes.reduce({}) do |sums, stats|
    sums.merge(stats) do |_, prev_hsh, new_hsh|
      prev_hsh.merge(new_hsh) {|_, prev_val, new_val| prev_val + new_val }
    end
  end
end

sum_stats(stats1, stats2, stats3)    
# => {
#   "Test1" => { "Variant A" => 1134, "Variant B" => 2264 },
#   "Test2" => { "Variant C" => 3323, "Variant D" => 4714 }
# }