Misha Moroshko Misha Moroshko - 4 months ago 38
Ruby Question

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

Why the following code issues an error ?


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:

=> 18


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