Fibers in Ruby 1.9

class Fib
  include Enumerable
  
  def initialize(stop_at)
    @count = 0
    @stop_at = stop_at
    @first, @second = 0, 1
    @fiber = Fiber.new do
      loop do
        @first, @second = @second, @first + @second
        @count += 1
        Fiber.yield @first
      end
    end
  end
  
  def next
    @fiber.resume
  end
  
  def rewind
    @first, @second = 0, 1
  end
  
  def each
    loop do
      @count == @stop_at ? break : yield(self.next)
    end
  end
end

# Print the first 20 fibonacci numbers
Fib.new(20).each do |elem|
  puts elem
end

Output

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
Sunday, January 3, 2010