为什么 Ruby 不注入 return 枚举器?

Why doesn't Ruby inject return an enumerator?

我原以为 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'

我原本希望按如下方式使用它:

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)

这样的实施有什么原因吗?

从概念上讲,Enumerator是一种集合。 Enumerable#inject 在集合的成员中累积一个值,return a Enumerator.

没有什么意义

您可以通过将 numbers.inject(0) &block 更改为:

来完成工作
numbers.inject(0, &block)

inject 等方法的重点是 return 一些基于枚举器的计算值。如果他们总是 return 一个枚举器,那么就没有有意义的用法。它 return 在块不存在时成为枚举器的原因是让您通过修改接收器来创建新的枚举器。不过,那不应该是最终的 objective;您只需创建一个枚举器,以便最终可以根据它计算出一些东西。