How to combine one hash with another hash in ruby

61,280

Solution 1

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

(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

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

Use merge method:

c = a.merge b
Share:
61,280
thefonso
Author by

thefonso

Look past the surface and assume only the positive. Force people to prove themselves other wise.

Updated on July 27, 2022

Comments

  • thefonso
    thefonso almost 2 years

    I have two hashes...

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

    I want...

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

    How do I create hash c?