Here's how to use the new Fiber class (warning: class name may change) to generate an infinite sequence of Fibonacci numbers. I use "generate" in the sense of Python's generators. Ruby's new fibers are "semi-coroutines"
fib = Fiber.new do
x, y = 0, 1
loop do
Fiber.yield y
x,y = y,x+y
end
end
20.times { puts fib.resume }
Remember that the Fiber class was added to Ruby 1.9 yesterday, so you need a very recent snapshot to make this work.
Here's a slightly higher-level way to do the Fibonacci numbers. We hide the Fiber class inside of a Generator class:
class Generator
def initialize &block
@f = Fiber.new &block
end
def next?
@f.alive?
end
def next(*args)
@f.resume(*args)
end
end
fib2 = Generator.new do
x, y = 0, 1
loop do
Fiber.yield y
x,y = y,x+y
end
end
20.times { puts fib2.next }



