Misha Moroshko Misha Moroshko - 5 days ago 6
Ruby Question

Why Ruby inject method cannot sum up string lengths without initial value?

Why the following code issues an error ?

['hello','stack','overflow'].inject{|memo,s|memo+s.length}

TypeError: can't convert Fixnum into String
from (irb):2:in `+'
from (irb):2:in `block in irb_binding'
from (irb):2:in `each'
from (irb):2:in `inject'
from (irb):2


If the initial value is passed, it works OK:

['hello','stack','overflow'].inject(0){|memo,s|memo+s.length}
=> 18

Answer

You have the answer in apidock :

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

That is, without an initial value, you're trying to do 'hello' + 'stack'.length

Comments