加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:55:25 所属栏目:百科 来源:网络整理
导读:为什么以下代码发出错误? ['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
为什么以下代码发出错误?
['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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读