Dan Rubio Dan Rubio -5 years ago 77
Ruby Question

Why does storing intermediary sums break my use of Ruby's inject method?

I want to use

and also store intermediary values in an array. Here is the code:

store_value = []
[1,2,3].inject(0) do |sum, n|
store_value << sum + n

I get this error:

no implicit conversion of Fixnum into Array (TypeError)

I don't understand why. Why doesn't this work?

Answer Source

The block passed to inject needs to return the memo (sum in your case). Appending to an array returns the array, not the value appended. So, in your code, the first time the block is executed sum becomes [1], and the second time it's executed sum + n is [1] + 2, which gives you the error you see.

Fix it by returning the sum from the block:

store_value = []
[1,2,3].inject(0) do |sum, n|
  sum += n
  store_value << sum
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download