Array#take_while
arr.take_while { |element| block } -> array Returns:
Array · Updated March 13, 2026 · Array Methods arrays elements slicing enumerable
take_while returns elements from the beginning of an array as long as the block returns truthy. It stops at the first falsy result.
Syntax
arr.take_while { |element| block }
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | Proc | Required | A block that evaluates each element. Returns truthy to keep, falsy to stop. |
Examples
Basic usage
numbers = [1, 2, 4, 8, 16, 32, 64]
# Take elements while they are less than 20
numbers.take_while { |n| n < 20 }
# => [1, 2, 4, 8, 16]
# Stop at first falsy result
words = ["one", "two", "three", "four", "five"]
words.take_while { |w| w.length < 5 }
# => ["one", "two"]
With empty arrays
empty = []
empty.take_while { |x| x }
# => []
Processing sorted data
temperatures = [15, 18, 22, 25, 28, 30, 29, 27, 24, 20]
# Get cold days
cold_days = temperatures.take_while { |t| t < 25 }
# => [15, 18, 22]
Block evaluation stops at first falsy
data = [1, 2, 3, 4, 5]
# Stops at 3, never evaluates 4 or 5
data.take_while do |n|
puts "checking #{n}"
n < 3
end
# checking 1
# checking 2
# checking 3
# => [1, 2]