Method: Array#collect

Defined in:
array.c

#collect {|element| ... } ⇒ Object #collectObject #map {|element| ... } ⇒ Object #mapObject

With a block given, calls the block with each element of self; returns a new array whose elements are the return values from the block:

a = [:foo, 'bar', 2]
a1 = a.map {|element| element.class }
a1 # => [Symbol, String, Integer]

With no block given, returns a new Enumerator.

Related: #collect!; see also Methods for Converting.

Overloads:

  • #collect {|element| ... } ⇒ Object

    Yields:

    • (element)
  • #map {|element| ... } ⇒ Object

    Yields:

    • (element)


3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
# File 'array.c', line 3636

static VALUE
rb_ary_collect(VALUE ary)
{
    long i;
    VALUE collect;

    RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
    collect = rb_ary_new2(RARRAY_LEN(ary));
    for (i = 0; i < RARRAY_LEN(ary); i++) {
        rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
    }
    return collect;
}