Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#take_while

() { (Elem obj) -> ::boolish } -> ::Array[Elem]
() -> ::Enumerator[Elem, ::Array[Elem]]
take_while {|element| ... } → new_array
take_while → new_enumerator

With a block given, calls the block with each successive element of self; stops iterating 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.take_while {|element| false }       # => []

With no block given, returns a new Enumerator.

Does not modify self.

Related: see Methods for Fetching.

Ruby version changes

  1. 3.0
See also #take #to_a #sum #to_ary also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0