Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get each value of inject loop

Tags:

ruby

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?

like image 339
ironsand Avatar asked Oct 08 '16 08:10

ironsand


2 Answers

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
like image 138
Aleksei Matiushkin Avatar answered Sep 22 '22 05:09

Aleksei Matiushkin


The best I could think

def partial_sums(arr, start = 0)
  sum = 0
  arr.each_with_object([]) do |elem, result|
    sum = elem + (result.empty? ? start : sum)
    result << sum
  end
end

partial_sums([1,2,3], 3)
like image 45
Ursus Avatar answered Sep 24 '22 05:09

Ursus