Ruby 为什么chunk_在返回枚举器对象时

Ruby 为什么chunk_在返回枚举器对象时,ruby,Ruby,为什么chunk\u同时返回枚举器的实例 此代码: array = [0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16] p array.chunk_while {|i,j| i + 1 == j } 输出如下: #<Enumerator::Generator:0x00000002bef0a8>:each> #:每个> 我有ruby版本ruby 2.3.1p112(2016-04-26修订版54768)[x64-mingw32]模块中的方法,例如chun

为什么
chunk\u同时
返回
枚举器的实例

此代码:

array = [0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16]
p array.chunk_while {|i,j| i + 1 == j }
输出如下:

#<Enumerator::Generator:0x00000002bef0a8>:each>
#:每个>
我有ruby版本
ruby 2.3.1p112(2016-04-26修订版54768)[x64-mingw32]

模块中的方法,例如
chunk\u,而
要求接收者是枚举器,即类的实例。因此,如果一个
可枚举
方法(如
chunk_,而
返回一个枚举数),它可以是另一个
可枚举
方法的接收者(该方法可以是另一个
可枚举
方法的接收者,等等)。这称为方法链接。这就是为什么您会看到许多
可枚举的
方法在没有提供块的情况下返回枚举数

将枚举数作为接收器的方法的链接也可能包括其他模块或类
枚举数中的方法,例如

这就是为什么我们可以编写如下表达式

array.chunk_while {|i,j| i + 1 == j }.map.with_index { |a,i| i.even? ? a.reduce(:+) : 0 }
  #=> [15, 0, 31]
让我们来分析一下

e0 = array.chunk_while {|i,j| i + 1 == j }
  #=> #<Enumerator: #<Enumerator::Generator:0x007fa01b9639e0>:each> 
e1 = e0.map
  #=> #<Enumerator: #<Enumerator: #<Enumerator::Generator:0x007fa01b9639e0>:each>:map> 
e2 = e1.with_index
  #=> #<Enumerator: #<Enumerator: #<Enumerator:
  #    #<Enumerator::Generator:0x007fa01b9639e0>:each>:map>:with_index> 
e2.each { |a,i| i.even? ? a.reduce(:+) : 0 }
  #=> [15, 0, 31] 

但是Ruby帮你省去了麻烦。当Ruby看到在数组上调用的方法需要一个枚举数作为其接收器时,它将为您调用。所有类都有一个方法
每个

你想查看枚举器中的所有元素吗?或者,简单的回答是:因为这样说。
array.each.chunk_while {|i,j| i + 1 == j }.to_a