Reputation: 373
I have a hash table that was created from a .txt file. Certain elements in the hash table has the same key. Ruby takes the last instance and uses that value in the hash table. How would I go about adding the values of duplicate keys together?
For example, if I have a hash table: hash = { a => 1, a => 2, b => 3 }
I would like the resulting hash table to be: hash = { a => 3, b => 3 }
Upvotes: 0
Views: 1472
Reputation: 84393
If you want to replace the values in your current hash by adding them together with the values associated with duplicate keys stored in another hash, you probably want to use the block form of Hash#update. The block defines what to do with duplicate keys; in this case, we simply add their values together. For example:
h1 = { a: 1, b: 3 }
h2 = { a: 2 }
h1.update(h2) { |k, v1, v2| v1 + v2 }
# => {:a=>3, :b=>3}
Note that this is an in-place change; you're actually modifying the values in h1. If you want to return a new hash with the merged values rather than overwriting h1, just use Hash#merge instead of Hash#update.
Upvotes: 3