Rails / ruby ​​combine two hashes with the same key, different values

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

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

and the second hash looks like this:

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

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

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

Is there an easy way to combine these two hashes, or do I need to iterate over the hashes each time and find this key in another hash?

+4
source share
1 answer

The easiest way is to turn hash arrays into 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, create an 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"}]}]
+10
source

All Articles