How to combine one hash with another hash in ruby
I have two hashes...
a = {:a => 5}
b = {:b => 10}
I want...
c = {:a => 5,:b => 10}
How do I create hash c?
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.
(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()