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 }

相关文章:

  • 2021-09-30
  • 2021-08-14
  • 2022-12-23
  • 2021-06-30
  • 2021-05-09
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-29
  • 2022-12-23
  • 2022-01-31
  • 2021-05-28
相关资源
相似解决方案