From: Jenda Krynicky Date: 2007-03-16T00:14:42+09:00 Subject: Re: non-destructive merging of hashes in array Giles Bowkett wrote: > Hi, I have an array of hashes. The keys in the hashes represent the same > things. > > eg: > > h1 = {:rabbits => 5} > h2 = {:rabbits => 10} > > bunnies = [h1, h2] > > I want to end up with this: > > {:rabbits => 15} res = Hash.new(0) # to give the new keys a sensible default bunnies.each {|arr| arr.each { | key, value | res[key] += value }} P.S.: I thought about res = {} bunnies.each {|arr| arr.each { | key, value | (res[key]||=0) += value }} but (res[key]||=0) is not a lvalue. It was even considered a syntax error with the helpfull error message of: syntax error, unexpected tOP_ASGN, expecting '}' -- Posted via http://www.ruby-forum.com/.