Created
December 22, 2011 20:05
-
-
Save fabiokung/1511648 to your computer and use it in GitHub Desktop.
fibers as generators
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
module Generators | |
def generator(&blk) | |
Fiber.new do | |
loop { Fiber.yield(blk.call) } | |
end | |
end | |
end |
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 "generators" | |
class Tokenizer | |
include Generators | |
def initialize | |
@tokens = [:a, :b, :c].each # File.open, Socket.new, ... | |
@generator = generator { @tokens.next } | |
end | |
def emit | |
@generator.resume | |
end | |
end | |
t = Tokenizer.new | |
t.emit | |
# => :a | |
t.emit | |
# => :b | |
t.emit | |
# => :c | |
t.emit | |
# => nil | |
# PS: http://ruby-doc.org/core/Enumerator.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment