Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails/ruby merge two hashes with same key, different values

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?

like image 652
user3344199 Avatar asked Dec 26 '22 06:12

user3344199


1 Answers

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"}]}]
like image 161
Uri Agassi Avatar answered Jan 14 '23 03:01

Uri Agassi