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!)
Note that with this solution, if two hashes in the source array have duplicate keys, those coming later in the array will take priority and overwrite the duplicate keys from earlier in the array:
[{"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.
animals
is a Hash with a single entry? Is it guaranteed that there are no duplicates or clashes? \$\endgroup\$