How to merge Ruby hashes

How can I merge these two hashes:

{:car => {:color => "red"}}
{:car => {:speed => "100mph"}}

To get:

{:car => {:color => "red", :speed => "100mph"}}

There is a Hash#merge method:

ruby-1.9.2 > a = {:car => {:color => "red"}}
 => {:car=>{:color=>"red"}} 
ruby-1.9.2 > b = {:car => {:speed => "100mph"}}
 => {:car=>{:speed=>"100mph"}} 
ruby-1.9.2 > a.merge(b) {|key, a_val, b_val| a_val.merge b_val }
 => {:car=>{:color=>"red", :speed=>"100mph"}} 

You can create a recursive method if you need to merge nested hashes:

def merge_recursively(a, b)
  a.merge(b) {|key, a_item, b_item| merge_recursively(a_item, b_item) }
end

ruby-1.9.2 > merge_recursively(a,b)
 => {:car=>{:color=>"red", :speed=>"100mph"}} 

Hash#deep_merge

Rails 3.0+

a = {:car => {:color => "red"}}
b = {:car => {:speed => "100mph"}}
a.deep_merge(b)
=> {:car=>{:color=>"red", :speed=>"100mph"}} 

Source: https://speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-do Slide 24

Also,

http://apidock.com/rails/v3.2.13/Hash/deep_merge


You can use the merge method defined in the ruby library. https://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge


Example

h1={"a"=>1,"b"=>2} 
h2={"b"=>3,"c"=>3} 
h1.merge!(h2)

It will give you output like this {"a"=>1,"b"=>3,"c"=>3}

Merge method does not allow duplicate key, so key b will be overwritten from 2 to 3.

To overcome the above problem, you can hack merge method like this.

h1.merge(h2){|k,v1,v2|[v1,v2]}

The above code snippet will be give you output

{"a"=>1,"b"=>[2,3],"c"=>3}