new(*args) public

Creates a new Enumerator object, which is to be used as an Enumerable object iterating in a given way.

In the first form, a generated Enumerator iterates over the given object using the given method with the given arguments passed. Use of this form is discouraged. Use Kernel#enum_for(), alias to_enum, instead.

e = Enumerator.new(ObjectSpace, :each_object)
    #-> ObjectSpace.enum_for(:each_object)

e.select { |obj| obj.is_a?(Class) }  #=> array of all classes

In the second form, iteration is defined by the given block, in which a “yielder” object given as block parameter can be used to yield a value by calling the yield method, alias +<<+.

fib = Enumerator.new { |y|
  a = b = 1
  loop {
    y << a
    a, b = b, a + b
  }
}

p fib.take(10) #=> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Show source
Register or log in to add new notes.