Is there a native way to join all elements of an array into a unique element like so:
[
{a: "a"},
{b: "b"}
].join do | x, y |
x.merge(y)
end
To output something like:
{
a: "a",
b: "b"
}
The fact that I used hashes into my array is an example, I could say:
[
0,
1,
2,
3
].join do | x, y |
x + y
end
Ends up with 6
as a value.
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
"sums" an array using the provided method. In the first case, the "addition" of the sum and the current element is done by merging, and in the second case, through addition.
If the array is empty, inject
returns nil
. To make it return something else, specify an initial value (thanks @Hellfar):
[].inject(0, :+) #=> 0
[
{a: "a"},
{b: "b"}
].inject({}){|sum, e| sum.merge e}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With