Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Array#select
() { (Elem element) -> ::boolish } -> ::Array[Elem]
() -> ::Enumerator[Elem, ::Array[Elem]]
select {|element| ... } → new_array
select → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_select(VALUE ary)
{
VALUE result;
rb_len_t 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;
}
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:
Example
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.