Attach an array with a block initially

Is there a custom way to combine all elements of the array into a unique element:

[
  {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 in my array is an example, I can say:

[
  0,
  1,
  2,
  3
].join do | x, y |
  x + y
end

Ends in 6like value.

+4
source share
2 answers

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
+5
source
[
  {a: "a"},
  {b: "b"}
].inject({}){|sum, e| sum.merge e}
+3
source

Source: https://habr.com/ru/post/1663534/


All Articles