gpt4 book ai didi

ruby - 为什么 Ruby 注入(inject)方法不能对没有初始值的字符串长度求和?

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:51 25 4
gpt4 key购买 nike

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

['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','stack','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

关于ruby - 为什么 Ruby 注入(inject)方法不能对没有初始值的字符串长度求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com