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

前端 未结 3 978
说谎
说谎 2020-12-18 06:39

Why the following code issues an error ?

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

TypeError: can\'t convert Fixnum into String
              


        
3条回答
  •  情歌与酒
    2020-12-18 07:01

    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

提交回复
热议问题