为什么Ruby注入方法不能总结没有初始值的字符串长度? [英] Why Ruby inject method cannot sum up string lengths without initial value?

查看:39
本文介绍了为什么Ruby注入方法不能总结没有初始值的字符串长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码会报错?

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

推荐答案

apidock :

如果没有明确指定memo的初始值,那么使用集合的第一个元素作为memo的初始值.

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

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

这篇关于为什么Ruby注入方法不能总结没有初始值的字符串长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆