Misha Moroshko Misha Moroshko - 1 year ago 71
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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download