Method: Array#select

Defined in:
array.c

#select {|element| ... } ⇒ Object #selectObject

Calls the block, if given, with each element of self; returns a new Array containing those elements of self for which the block returns a truthy value:

a = [:foo, 'bar', 2, :bam]
a1 = a.select {|element| element.to_s.start_with?('b') }
a1 # => ["bar", :bam]

Returns a new Enumerator if no block given:

a = [:foo, 'bar', 2, :bam]
a.select # => #<Enumerator: [:foo, "bar", 2, :bam]:select>

Array#filter is an alias for Array#select.

Overloads:

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

    Yields:

    • (element)


3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
# File 'array.c', line 3792

static VALUE
rb_ary_select(VALUE ary)
{
    VALUE result;
    long i;

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