我想合并两个哈希。它们看起来像这样:
[{"Hello"->"3"},{"Hi"->"43"},{"Hola"->"43"}]
,第二个哈希看起来像:
[{"Hello"->"4"},{"Hi"->"2"},{"Bonjour"->"2"}]
我想合并这两个哈希数组,结果如下:
[{"Hello"->[{value1=>3},{value2=>4}],{"Hi"->[{value1=>43},{value2=>2}]},{"Bonjour"->[{value1=>0},{value2=>2}]},{"Hola"->[{value1=>43},{value2=>0}]]
是否有一种简单的方法来合并这两个哈希值,还是我必须单独遍历哈希值并在另一个哈希值中找到该键?
答案 0 :(得分:10)
最简单的方法是将哈希数组转换为哈希值:
h1 = a1.reduce(&:merge)
# => {"Hello"=>"3", "Hi"=>"43", "Hola"=>"43"}
h2 = a2.reduce(&:merge)
# => {"Hello"=>"4", "Hi"=>"2", "Bonjour"=>"2"}
然后你需要找到所有的键:
keys = [h1, h2].flat_map(&:keys).uniq
# => ["Hello", "Hi", "Hola", "Bonjour"]
接下来,对于每个键,构建值数组:
keys.map do |k|
{k => [{value1: h1[k] || "0"},
{value2: h2[k] || "0"}]}
end
# => [{"Hello"=>[{:value1=>"3"}, {:value2=>"4"}]},
# {"Hi"=>[{:value1=>"43"}, {:value2=>"2"}]},
# {"Hola"=>[{:value1=>"43"}, {:value2=>"0"}]},
# {"Bonjour"=>[{:value1=>"0"}, {:value2=>"2"}]}]