Mar
9th
2010
Tue
9th
2010
Hash manipulations in ruby
I was looking around for an easy way to sum the individual elements in a hash without referencing the individual keys. It turns out that there’s an easy way to do this - just pass a block to hash.merge and you get access the key, old, and new values. From there, summing the keys is easy:
>> hash1
=> {:one=>5, :two=>10, :three=>3}
>> hash2
=> {:four=>4, :one=>1, :two=>2}
>> hash1.merge(hash2)
=> {:four=>4, :one=>1, :two=>2, :three=>3}
>> hash1.merge(hash2) {|k, o, n| o + n}
=> {:four=>4, :one=>6, :two=>12, :three=>3}