当前位置: 首页 > 工具软件 > Ruby-Enum > 使用案例 >

ruby 1.9 中 to_enum的实现

魏翰
2023-12-01

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 }

转载于:https://www.cnblogs.com/orez88/articles/1439808.html

 类似资料: