Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#take_while

enum.take_while { |obj| block } → array
enum.take_while → an_enumerator

Passes elements to the block until the block returns nil or false, then stops iterating and returns an array of all prior elements.

If no block is given, an enumerator is returned instead.

Example
a = [1, 2, 3, 4, 5, 0]
a.take_while { |i| i < 3 }   #=> [1, 2]
See also #take #tally #sum #to_a also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1