这个问题不是关于如何在
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
在上面的代码中,我可以使用e = Bunk.new.each,然后使用e.next,e.next来获取每个连续的元素,但是它究竟是如何暂停执行然后在正确的位置恢复?
我知道如果0.upto的产量被Fiber.yield取代,那么它很容易理解,但这不是这里的情况.这是一个普通的老产量,它是如何工作的?
我看了一下enumerator.c,但对我来说这是不可理解的.也许有人可以在Ruby中提供一个实现,使用光纤,而不是1.8.6样式的基于延续的枚举器,这一切都清楚了吗?
解决方法
这是一个普通的ruby枚举器,它使用Fibers,并且应该像原始行为一样:
- 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
在有人抱怨异常作为流控制之前:真正的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]]