ironsand ironsand - 2 months ago 16
Ruby Question

How to get each value of inject loop

I want to get each value of

inject
.

For example
[1,2,3].inject(3){|sum, num| sum + num}
returns
9
, and I want to get all values of the loop.
I tryed
[1,2,3].inject(3).map{|sum, num| sum + num}
, but it didn't work.

The code I wrote is this, but I feel it's redundant.

a = [1,2,3]
result = []
a.inject(3) do |sum, num|
v = sum + num
result << v
v
end

p result
# => [4, 6, 9]


Is there a way to use
inject
and
map
at same time?

Answer

Using a dedicated Eumerator perfectly fits here, but I would show more generic approach for this:

[1,2,3].inject(map: [], sum: 3) do |acc, num|
  acc[:map] << (acc[:sum] += num)
  acc
end
#⇒ => {:map => [4, 6, 9], :sum => 9}

That way (using hash as accumulator) one might collect whatever she wants. Sidenote: better use Enumerable#each_with_object here instead of inject, because the former does not produce a new instance of an object on each subsequent iteration:

[1,2,3].each_with_object(map: [], sum: 3) do |num, acc|
  acc[:map] << (acc[:sum] += num)
end