How to merge Ruby hashes

RubyHashmap

Ruby Problem Overview


How can I merge these two hashes:

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

To get:

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

Ruby Solutions


Solution 1 - Ruby

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"}} 

Solution 2 - Ruby

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

Solution 3 - Ruby

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}

Solution 4 - Ruby

h1 = {:car => {:color => "red"}}
h2 = {:car => {:speed => "100mph"}}
h3 = h1[:car].merge(h2[:car])
h4 = {:car => h3}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskyporterView Question on Stackoverflow
Solution 1 - RubyAliaksei KliuchnikauView Answer on Stackoverflow
Solution 2 - RubyAndreiView Answer on Stackoverflow
Solution 3 - RubyMukesh Kumar GuptaView Answer on Stackoverflow
Solution 4 - Rubybor1sView Answer on Stackoverflow