Class: Enumerable::Enumerator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
enumerator.c

Overview

A class which provides a method 'each' to be used as an Enumerable object.

Instance Method Summary collapse

Constructor Details

#Enumerable::Enumerator.new(obj, method = :each, *args) ⇒ Object

Creates a new Enumerable::Enumerator object, which is to be used as an Enumerable object using the given object's given method with the given arguments.

e.g.:

str = "xyz"

enum = Enumerable::Enumerator.new(str, :each_byte)
a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]


# File 'enumerator.c'

static VALUE
enumerator_initialize(argc, argv, obj)
    int argc;
    VALUE *argv;
    VALUE obj;
{
    VALUE enum_obj, enum_method, enum_args;

    rb_scan_args(argc, argv, "11*", &enum_obj, &enum_method, &enum_args);

    if (enum_method == Qnil)
    enum_method = sym_each;

    rb_ivar_set(obj, id_enum_obj, enum_obj);
    rb_ivar_set(obj, id_enum_method, enum_method);
    rb_ivar_set(obj, id_enum_args, enum_args);

    return Qnil;
}

Instance Method Details

#each { ... } ⇒ Object

Iterates the given block using the object and the method specified in the first place.

Yields:



# File 'enumerator.c'

static VALUE
enumerator_each(obj)
    VALUE obj;
{
    VALUE val;

    obj = (VALUE)rb_node_newnode(NODE_MEMO,
                 rb_ivar_get(obj, id_enum_obj),
                 rb_to_id(rb_ivar_get(obj, id_enum_method)),
                 rb_ivar_get(obj, id_enum_args));
    val = rb_iterate((VALUE (*)_((VALUE)))enumerator_iter, obj, rb_yield, 0);
    return val;
}