Last active
November 22, 2016 19:10
-
-
Save mark/0bf209dc1bf5584b1b4fcc32cdc612f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'fiber' | |
require 'pp' | |
class MyWrapper | |
include Enumerable | |
def initialize | |
@fiber = fiber | |
@results = [] | |
end | |
def each | |
@results.each { |obj| yield obj } | |
while @fiber.alive? | |
obj = @fiber.resume | |
@results << obj | |
yield obj | |
end | |
end | |
private | |
def fiber | |
Fiber.new do | |
10.times do |i| | |
puts "CREATING #{i}" | |
Fiber.yield(i) | |
end | |
end | |
end | |
end | |
e = MyWrapper.new | |
pp e.take(3) | |
# CREATING 0 | |
# CREATING 1 | |
# CREATING 2 | |
#=> [0, 1, 2] | |
pp e.take(5) | |
# CREATING 3 | |
# CREATING 4 | |
#=> [0, 1, 2, 3, 4] | |
pp e.take(10) | |
# CREATING 5 | |
# CREATING 6 | |
# CREATING 7 | |
# CREATING 8 | |
# CREATING 9 | |
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment