枚举器如何在Ruby 1.9.1中工作?

hor*_*guy 8 ruby enumerators fiber ruby-1.9

这个问题不是关于如何在Ruby 1.9.1中使用枚举器,而是我很好奇它们是如何工作的.这是一些代码:

class Bunk
  def initialize
    @h = [*1..100]
  end

  def each
    if !block_given?
      enum_for(:each)
    else
      0.upto(@h.length) { |i|
        yield @h[i]
      }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我可以使用e = Bunk.new.each,然后e.next,e.next获取每个连续的元素,但它究竟是如何暂停执行然后在正确的位置恢复?

我知道,如果0.uptoFiber.yield它替换的产量很容易理解,但这不是这里的情况.这是一个普通的老yield,所以它是如何工作的?

我看了enumerator.c,但对我来说这是不可理解的.也许有人可以在Ruby中提供一个实现,使用光纤,而不是1.8.6样式的基于延续的枚举器,这一切都清楚了吗?

sep*_*p2k 14

这是一个使用Fibers的普通ruby枚举器,它的行为应该与原始的一样:

class MyEnumerator
  include Enumerable

  def initialize(obj, iterator_method)
    @f = Fiber.new do
      obj.send(iterator_method) do |*args|
        Fiber.yield(*args)
      end
      raise StopIteration
    end
  end

  def next
    @f.resume
  end

  def each
    loop do
      yield self.next
    end
  rescue StopIteration
    self
  end
end
Run Code Online (Sandbox Code Playgroud)

在有人抱怨异常作为流控制之前:真正的Enumerator也会在最后引发StopIteration,所以我只是模仿了原来的行为.

用法:

>> enum = MyEnumerator.new([1,2,3,4], :each_with_index)
=> #<MyEnumerator:0x9d184f0 @f=#<Fiber:0x9d184dc>
>> enum.next
=> [1, 0]
>> enum.next
=> [2, 1]
>> enum.to_a
=> [[3, 2], [4, 3]]
Run Code Online (Sandbox Code Playgroud)