Array#select
arr.select { |element| block } -> new_array Returns:
Array · Updated March 13, 2026 · Array Methods ruby arrays enumerable filtering
Array#select filters array elements based on a condition you define in a block. It returns a new array containing only the elements for which the block evaluates to truthy. This is one of the most common methods for extracting subsets of data from arrays.
The key thing to remember: select only includes elements where the block returns a truthy value (true or anything other than nil or false). It never modifies the original array.
Syntax
array.select { |element| block }
array.select # without block returns an Enumerator
When you omit the block, select returns an Enumerator, which lets you chain other Enumerable methods or use it with control flow structures.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | Proc | Required | A block that receives each element. Return truthy to include the element, falsy to exclude it. |
Return Value
Returns a new Array containing all elements for which the block returned a truthy value. The original array remains unchanged. Returns an empty array if no elements match.
Examples
Basic filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get only even numbers
evens = numbers.select { |n| n.even? }
# => [2, 4, 6, 8, 10]
# Get numbers greater than 5
greater_than_five = numbers.select { |n| n > 5 }
# => [6, 7, 8, 9, 10]
Filtering strings
words = ["apple", "banana", "cherry", "date", "elderberry"]
# Get words longer than 5 characters
long_words = words.select { |w| w.length > 5 }
# => ["banana", "cherry", "elderberry"]
# Get words containing the letter 'a'
has_a = words.select { |w| w.include?('a') }
# => ["apple", "banana", "date"]
Filtering with ranges
numbers = [1, 5, 10, 15, 20, 25, 30]
# Select numbers in a specific range
in_range = numbers.select { |n| n.between?(10, 20) }
# => [10, 15, 20]
See Also
- Array#find — returns the first element that matches
- Array#map — transforms each element