Dan Rubio Dan Rubio - 1 year ago 65
Ruby Question

Why can't I see the intermediary sums for Ruby's inject method?

I'm trying to solve a kata and for this kata I want to store intermediary values in an array for

but I always get this error:

no implicit conversion of Fixnum into Array (TypeError)

and I don't understand why. Here is the code:

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

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