Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created June 2, 2018 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/78e4f509fe1f6c9feeef33f3b222797f to your computer and use it in GitHub Desktop.
Save inopinatus/78e4f509fe1f6c9feeef33f3b222797f to your computer and use it in GitHub Desktop.
Block yielding to a block, via fibers.
# importer/exporter interaction via fibers
require 'fiber'
class Importer
DATA = [
["foo", "bar"],
["jazz", "quux"],
["cats", "dogs"]
]
def initialize
@data = DATA.dup.each
end
def import
loop do
yield(@data.next)
end
end
end
class Exporter
def export
loop do
value = yield
puts "exporting: #{value}"
end
end
end
importer = Importer.new
exporter = Exporter.new
fiber = Fiber.new do
importer.import { |v| Fiber.yield(v) }
raise StopIteration
end
exporter.export { fiber.resume }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment