arsenalist arsenalist - 3 months ago 7
Ruby Question

Why do I get a 'typeerror' when using inject in Ruby?

I am using this inject method to make a running total of values into an array. I am trying to figure out why I am getting an error.

def running_totals(myarray)
results = []
myarray.inject([]) do |sum,n|
results << sum + n
end
results
end

p running_totals([1,2,3,4,5])


I am getting the error

in `+': no implicit conversion of Fixnum into Array (TypeError)


When breaking this method down, isn't this the same as adding two integers and adding that into an array? I'm a bit confused here. Thanks for the help.

Answer

The result of results << sum + n is an array results and it's this that's replacing the sum value and so the next iteration you're trying to add a fixnum n into an array sum ... plus it doesn't help that you're initializing the value of sum to be an array.

Make sure that the last executed statement in your inject block is what you want the accumulated value to be.

def running_totals(myarray)
  results = []
  results << myarray.inject do |sum, n|
    results << sum
    sum + n
  end
  results
end

p running_totals([1,2,3,4,5])
=> [1, 3, 6, 10, 15]

Note that I moved the result of the inject into results array as well, so that the final value is also included, otherwise you'd only have the four values and would be missing the final (15) value.