/Ruby 2.7

class Enumerator::Chain


Enumerator::Chain is a subclass of Enumerator, which represents a chain of enumerables that works as a single enumerator.

This type of objects can be created by Enumerable#chain and Enumerator#+.

Public Class Methods

Enumerator::Chain.new(*enums) → enum Show source
static VALUE
enum_chain_initialize(VALUE obj, VALUE enums)
    struct enum_chain *ptr;

    TypedData_Get_Struct(obj, struct enum_chain, &enum_chain_data_type, ptr);

    if (!ptr) rb_raise(rb_eArgError, "unallocated chain");

    ptr->enums = rb_obj_freeze(enums);
    ptr->pos = -1;

    return obj;

Generates a new enumerator object that iterates over the elements of given enumerable objects in sequence.

e = Enumerator::Chain.new(1..3, [4, 5])
e.to_a #=> [1, 2, 3, 4, 5]
e.size #=> 5

Public Instance Methods

each(*args) { |...| ... } → obj Show source
each(*args) → enumerator
static VALUE
enum_chain_each(int argc, VALUE *argv, VALUE obj)
    VALUE enums, block;
    struct enum_chain *objptr;
    long i;

    RETURN_SIZED_ENUMERATOR(obj, argc, argv, argc > 0 ? enum_chain_enum_no_size : enum_chain_enum_size);

    objptr = enum_chain_ptr(obj);
    enums = objptr->enums;
    block = rb_block_proc();

    for (i = 0; i < RARRAY_LEN(enums); i++) {
        objptr->pos = i;
        rb_funcall_with_block(RARRAY_AREF(enums, i), id_each, argc, argv, block);

    return obj;

Iterates over the elements of the first enumerable by calling the “each” method on it with the given arguments, then proceeds to the following enumerables in sequence until all of the enumerables are exhausted.

If no block is given, returns an enumerator.

inspect → string Show source
static VALUE
enum_chain_inspect(VALUE obj)
    return rb_exec_recursive(inspect_enum_chain, obj, 0);

Returns a printable version of the enumerator chain.

rewind → obj Show source
static VALUE
enum_chain_rewind(VALUE obj)
    struct enum_chain *objptr = enum_chain_ptr(obj);
    VALUE enums = objptr->enums;
    long i;

    for (i = objptr->pos; 0 <= i && i < RARRAY_LEN(enums); objptr->pos = --i) {
        rb_check_funcall(RARRAY_AREF(enums, i), id_rewind, 0, 0);

    return obj;

Rewinds the enumerator chain by calling the “rewind” method on each enumerable in reverse order. Each call is performed only if the enumerable responds to the method.

size → int, Float::INFINITY or nil Show source
static VALUE
enum_chain_size(VALUE obj)
    return enum_chain_total_size(enum_chain_ptr(obj)->enums);

Returns the total size of the enumerator chain calculated by summing up the size of each enumerable in the chain. If any of the enumerables reports its size as nil or Float::INFINITY, that value is returned as the total size.

Ruby Core © 1993–2017 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.