Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Array#take_while
array.take_while {|element| ... } → new_array
array.take_while → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_take_while(VALUE ary)
{
long i;
RETURN_ENUMERATOR(ary, 0, 0);
for (i = 0; i < RARRAY_LEN(ary); i++) {
if (!RTEST(rb_yield(RARRAY_AREF(ary, i)))) break;
}
return rb_ary_take(ary, LONG2FIX(i));
}
Returns a new Array containing zero or more leading elements of self; does not modify self.
With a block given, calls the block with each successive element of self; stops if the block returns false or nil; returns a new Array containing those elements for which the block returned a truthy value:
Example
a = [0, 1, 2, 3, 4, 5] a.take_while {|element| element < 3 } # => [0, 1, 2] a.take_while {|element| true } # => [0, 1, 2, 3, 4, 5] a # => [0, 1, 2, 3, 4, 5]
With no block given, returns a new Enumerator:
Example
[0, 1].take_while # => #<Enumerator: [0, 1]:take_while>