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