How to combine one hash with another hash in ruby

RubyHashmap

Ruby Problem Overview


I have two hashes...

a = {:a => 5}
b = {:b => 10}

I want...

c = {:a => 5,:b => 10}

How do I create hash c?

Ruby Solutions


Solution 1 - Ruby

It's a pretty straight-forward operation if you're just interleaving:

c = a.merge(b)

If you want to actually add the values together, this would be a bit trickier, but not impossible:

c = a.dup
b.each do |k, v|
  c[k] ||= 0
  c[k] += v
end

The reason for a.dup is to avoid mangling the values in the a hash, but if you don't care you could skip that part. The ||= is used to ensure it starts with a default of 0 as nil + 1 is not valid.

Solution 2 - Ruby

(TL;DR: hash1.merge(hash2))

As everyone is saying you can use merge method to solve your problem. However there is slightly some problem with using the merge method. Here is why.

person1 = {"name" => "MarkZuckerberg",  "company_name" => "Facebook", "job" => "CEO"}

person2 = {"name" => "BillGates",  "company_name" => "Microsoft", "position" => "Chairman"}

Take a look at these two fields name and company_name. Here name and company_name both are same in the two hashes(I mean the keys). Next job and position have different keys.

When you try to merge two hashes person1 and person2 If person1 and person2 keys are same? then the person2 key value will override the peron1 key value . Here the second hash will override the first hash fields because both are same. Here name and company name are same. See the result.

people  = person1.merge(person2)

 Output:  {"name"=>"BillGates", "company_name"=>"Microsoft", 
        "job"=>"CEO", "position"=>"Chairman"}

However if you don't want your second hash to override the first hash. You can do something like this

  people  = person1.merge(person2) {|key, old, new| old}

  Output:   {"name"=>"MarkZuckerberg", "company_name"=>"Facebook", 
            "job"=>"CEO", "position"=>"Chairman"} 

It is just a quick note when using merge()

Solution 3 - Ruby

I think you want

c = a.merge(b)

you can check out the docs at http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge

Solution 4 - Ruby

Use merge method:

c = a.merge b

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
QuestionthefonsoView Question on Stackoverflow
Solution 1 - RubytadmanView Answer on Stackoverflow
Solution 2 - RubyPrabhakar UndurthiView Answer on Stackoverflow
Solution 3 - RubyAndbdrewView Answer on Stackoverflow
Solution 4 - RubyjboursiquotView Answer on Stackoverflow