Enumerable#inject covers both of these cases:
a = [{a: "a"}, {b: "b"}]
a.inject(:merge) #=> {:a=>"a", :b=>"b"}
b = [0, 1, 2, 3]
b.inject(:+) #=> 6
inject"summarizes" the array using the provided method. In the first case, the “addition” of the amount and the current element is performed by merging, and in the second, by adding.
If the array is empty, injectreturns nil. To make it return something else, specify an initial value (thanks @Hellfar):
[].inject(0, :+) #=> 0
source
share