Using Generator in Ruby

By: James Edward Gray II Viewed: 153164 times    

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

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)

Comment on this tutorial