为什么Ruby注入不返回枚举器?

Jik*_*ose 1 ruby enumerable

我期待Enumerable#inject将像其他方法一样返回一个枚举器并将其传递给一个块; 但这是投掷错误.尝试以下方式pry:

>> numbers = (1..12)
=> 1..12
>> numbers.each_with_index
=> #<Enumerator: ...>
>> numbers.each_with_index.map
=> #<Enumerator: ...>
>> numbers.inject(0)
TypeError: 0 is not a symbol
from (pry):18:in `inject'
Run Code Online (Sandbox Code Playgroud)

我期待按如下方式使用它:

numbers = (1..12)
block = lambda { |sum, digit| sum + digit }

numbers.inject(0) { |sum, digit| sum + digit } # => 78
numbers.each_with_index.map &block # => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
numbers.inject(0) &block # => 0 is not a symbol (TypeError)
Run Code Online (Sandbox Code Playgroud)

这样的实施有什么理由吗?

Yu *_*Hao 5

从概念上讲,Enumerator是一种集合.Enumerable#inject在集合的成员之间累积一个值,它返回一个没什么意义Enumerator.

您可以通过更改numbers.inject(0) &block为:完成工作:

numbers.inject(0, &block)
Run Code Online (Sandbox Code Playgroud)