Adam Fields (work stuff) RSS

This is my blog about work stuff.

See this post for discussion of what this blog is about and what I do.

I am often available for consulting work, and always happy to discuss it even if I'm currently very busy. Email me or find me on twitter @fields if you need something.

Archive

Mar
9th
2010
Tue
permalink

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}

Comments (View)

blog comments powered by Disqus