为什么Ruby注入方法无法在没有初始值的情况下总结字符串长度?

为什么以下代码发出错误?
['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

如果传递初始值,则可以正常工作:

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

解决方法

你在 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.

也就是说,如果没有初始值,你就会尝试’hello”stack’.length

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...