rails/ruby merge two hashes with same key, differe

2019-05-07 08:00发布

I have two hashes that I would like to merge. they look like this:

[{"Hello"->"3"},{"Hi"->"43"},{"Hola"->"43"}]

and the second hash looks like:

[{"Hello"->"4"},{"Hi"->"2"},{"Bonjour"->"2"}]

I would like to merge these two hash arrays so that the result looks like:

[{"Hello"->[{value1=>3},{value2=>4}],{"Hi"->[{value1=>43},{value2=>2}]},{"Bonjour"->[{value1=>0},{value2=>2}]},{"Hola"->[{value1=>43},{value2=>0}]]

Is there a simple way to merge these two hashes or do I have to iterate through the hashes individually and find that key in the other hash?

1条回答
欢心
2楼-- · 2019-05-07 08:39

The easiest way is turn the arrays of hashes to hashes:

h1 = a1.reduce(&:merge)
# => {"Hello"=>"3", "Hi"=>"43", "Hola"=>"43"}
h2 = a2.reduce(&:merge)
# => {"Hello"=>"4", "Hi"=>"2", "Bonjour"=>"2"}

Then you need to find all the keys:

 keys = [h1, h2].flat_map(&:keys).uniq
 # => ["Hello", "Hi", "Hola", "Bonjour"]

Next, for each key, build the array of values:

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"}]}]
查看更多
登录 后发表回答