G
Giles Bowkett
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}
It's a trivial task, but what's the quickest way to get there? I'm
certain it can be done on one line.
I know there's a Hash#update, but it appears that it would just
replace the 10 with 5, or vice versa, rather than adding them up.
This works, but it seems clunky:
hashes.each do |h|
h.each do |k, v|
if new_hash[k]
new_hash[k] += v
else
new_hash[k] = v
end
end
end
It can be crammed all onto one line, too, but there must be a nicer way.
eg:
h1 = {:rabbits => 5}
h2 = {:rabbits => 10}
bunnies = [h1, h2]
I want to end up with this:
{:rabbits => 15}
It's a trivial task, but what's the quickest way to get there? I'm
certain it can be done on one line.
I know there's a Hash#update, but it appears that it would just
replace the 10 with 5, or vice versa, rather than adding them up.
This works, but it seems clunky:
hashes.each do |h|
h.each do |k, v|
if new_hash[k]
new_hash[k] += v
else
new_hash[k] = v
end
end
end
It can be crammed all onto one line, too, but there must be a nicer way.