Programming Tutorials

Using Generator in Ruby

By: James Edward Gray II in Ruby Tutorials on 2009-03-03  

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





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)