class Generator
def initialize(enumerable)
@enumerable = enumerable # Remember the enumerable object
create_fiber # Create a fiber to enumerate it
end
def next # Return the next element
@fiber.resume # by resuming the fiber
end
def rewind # Start the enumeration over
create_fiber # by creating a new fiber
end
private
def create_fiber # Create the fiber that does the enumeration
@fiber = Fiber.new do # Create a new fiber
@enumerable.each do |x| # Use the each method
Fiber.yield(x) # But pause during enumeration to return values
end
raise StopIteration # Raise this when we're out of values
end
end
end
g = Generator.new(1..10) # Create a generator from an Enumerable like this
loop { print g.next } # And use it like an enumerator like this
g = (1..10).to_enum # The to_enum method does the same thing
loop { print g.next }
g = (1..10).to_enum # The to_enum method does the same thing
loop { print g.next }