Trying to add values of same key but with iterating it. here is my array
arr = [ {a: 10, b: 5, c: 2}, {a: 5, c: 3}, { b: 15, c: 4}, {a: 2}, {} ]
Want to converted it like
{a: 17, b: 20, c: 9}
Trying to add values of same key but with iterating it. here is my array
arr = [ {a: 10, b: 5, c: 2}, {a: 5, c: 3}, { b: 15, c: 4}, {a: 2}, {} ]
Want to converted it like
{a: 17, b: 20, c: 9}
each_with_object
to the rescue:Here is one way to do this by making use of
Enumerable#reduce
andHash#merge
:#1 Use a "counting hash"
Edit: I just noticed that @Pascal posted the same solution earlier. I'll leave mine for the explanation.
h = Hash.new(0)
is a counting hash with a default value of zero. That means that ifh
does not have a keyk
,h[k]
returns zero (but the hash is not altered). Ruby expandsh[k] += 4
toh[k] = h[k] + 4
, so ifh
does not have a keyk
,h[k]
on the right side of the equality equals zero.#2 Use Hash#update
Specifically, use the form of this method (aka
merge!
) that employs a block to determine the values of keys that are present in both hashes being merged.