Arrays of hashes to hash

Task: convert this array of hashes:

animals = [
{"cats" => 3},
{"dogs" => 5 }
]


to this hash:

{
"cats" => 3,
"dogs" => 5
}


This is my solution, any feedback is appreciated :-)

animals.reduce({}) {|m,e|
e.each{|k,v| m[k] = v}; m
}

• You've given an example, but can you be more specific about the requirements and constraints? For example, is guaranteed that each element of animals is a Hash with a single entry? Is it guaranteed that there are no duplicates or clashes? – 200_success Jan 26 at 0:08
• no constraints, it just has to work with that example :-) – sekmo Jan 27 at 23:11

The snippet e.each{|k,v| m[k] = v} does the same thing as the standard library method Hash#merge!, so the shortest way to write your solution is probably:
animals.reduce({}, :merge!)

[{"egrets" => 17}, {"egrets" => 21}].reduce({}, :merge!)  # => {"egrets"=>21}

Also be aware that merge! is destructive to the original hash, which is fine here since we don't reuse the literal input to reduce. There is a non-destructive version, merge, which is better when the input needs to be preserved.