From: Rob Biedenharn Date: 2009-01-29T04:28:23+09:00 Subject: Re: "adding" two hashes On Jan 28, 2009, at 2:07 PM, Bryson Smith wrote: > Hi, > > I'm wondering if it is possible to "add" the values of two hashes > together. Suppose I had: > > hash1 = {:key_one=>100, :key_two=>200} > hash2 = {:key_two=>300, :key_three=>400} > > I'd like to "add" the hashes together so that I get > > result => {:key_one=>100, :key_two=>500, :key_three=>400} > > Do I need to write my own function to parse through each hash's keys? > Is there a built-in way to do this? > > Thanks! irb> hash1 = {:key_one=>100, :key_two=>200} => {:key_two=>200, :key_one=>100} irb> hash2 = {:key_two=>300, :key_three=>400} => {:key_two=>300, :key_three=>400} irb> result = hash1.merge(hash2) {|key,val1,val2| val1+val2} => {:key_two=>500, :key_three=>400, :key_one=>100} You only have to write the block that deals with the duplicates for 'key' -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com