Method: Array#filter

Defined in:
array.c

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

With a block given, calls the block 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]
a.select {|element| element.to_s.start_with?('b') }
# => ["bar", :bam]

With no block given, returns a new Enumerator.

Related: see Methods for Fetching.

Overloads:

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

    Yields:

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

    Yields:

    • (element)


3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
# File 'array.c', line 3877

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;
}