Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join an array with a block natively

Tags:

ruby

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.

like image 984
Hellfar Avatar asked Feb 05 '23 13:02

Hellfar


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 "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
like image 166
Linuxios Avatar answered Feb 20 '23 18:02

Linuxios


[
  {a: "a"},
  {b: "b"}
].inject({}){|sum, e| sum.merge e}
like image 38
Bustikiller Avatar answered Feb 20 '23 19:02

Bustikiller