Skip to content

Instantly share code, notes, and snippets.

@fabiokung
Created December 22, 2011 20:05
Show Gist options
  • Save fabiokung/1511648 to your computer and use it in GitHub Desktop.
Save fabiokung/1511648 to your computer and use it in GitHub Desktop.
fibers as generators
module Generators
def generator(&blk)
Fiber.new do
loop { Fiber.yield(blk.call) }
end
end
end
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