Method: Enumerator#initialize

Defined in:
enumerator.c

#new(obj, method = :each, *args) ⇒ Object #new {|y| ... } ⇒ Object

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]

Overloads:

  • #new {|y| ... } ⇒ Object

    Yields:

    • (y)

# File 'enumerator.c'

/*
 *  call-seq:
 *    Enumerator.new(obj, method = :each, *args)
 *    Enumerator.new { |y| ... }
 *
 *  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]
 */
static VALUE
enumerator_initialize(int argc, VALUE *argv, VALUE obj)
{
    VALUE recv, meth = sym_each;

    if (argc == 0) {
    if (!rb_block_given_p())
        rb_raise(rb_eArgError, "wrong number of argument (0 for 1+)");

    recv = generator_init(generator_allocate(rb_cGenerator), rb_block_proc());
    }
    else {
    recv = *argv++;
    if (--argc) {
        meth = *argv++;
        --argc;
    }
    }

    return enumerator_init(obj, recv, meth, argc, argv);
}