Class Generator
In: lib/generator.rb
Parent: Object

Generator converts an internal iterator (i.e. an Enumerable object) to an external iterator.

Note that it is not very fast since it is implemented using continuations, which are currently slow.

Example

  require 'generator'

  # Generator from an Enumerable object
  g = Generator.new(['A', 'B', 'C', 'Z'])

  while g.next?
    puts g.next
  end

  # Generator from a block
  g = Generator.new { |g|
    for i in 'A'..'C'
      g.yield i
    end

    g.yield 'Z'
  }

  # The same result as above
  while g.next?
    puts g.next
  end

Methods

current   each   end?   index   new   next   next?   pos   rewind   yield  

Included Modules

Enumerable

Public Class methods

Creates a new generator either from an Enumerable object or from a block.

In the former, block is ignored even if given.

In the latter, the given block is called with the generator itself, and expected to call the yield method for each element.

Public Instance methods

Returns the element at the current position.

Rewinds the generator and enumerates the elements.

Returns true if the generator has reached the end.

Returns the current index (position) counting from zero.

Returns the element at the current position and moves forward.

Returns true if the generator has not reached the end yet.

Returns the current index (position) counting from zero.

Rewinds the generator.

Yields an element to the generator.

[Validate]

ruby-doc.org is a service of James Britt and Neurogami, a Ruby application development company in Phoenix, AZ.

Documentation content on ruby-doc.org is provided by remarkable members of the Ruby community.

For more information on the Ruby programming language, visit ruby-lang.org.

Want to help improve Ruby's API docs? See Ruby Documentation Guidelines.