dbp
dbp

Reputation: 373

Add values of identical keys together in Ruby hash

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

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84393

Use Block Form of Hash#Update

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

Related Questions