Enumerable.find / find_all / detect
Methods for searching a collection for elements that match a condition. find returns the first matching element, while find_all returns all matching elements.
Syntax
# Returns the first element that matches the condition.
collection.find { |element| condition }
collection.detect { |element| condition } # Alias for find
# Returns all matching elements as an array.
collection.find_all { |element| condition }
collection.select { |element| condition } # Alias for find_all
# Returns all elements that do NOT match the condition.
collection.reject { |element| condition }
Method List
| Method | Description |
|---|---|
| find | Returns the first element that matches the condition. Returns nil if no match is found. |
| detect | An alias for find. Behaves identically. |
| find_all | Returns all matching elements as an array. Returns an empty array if no match is found. |
| select | An alias for find_all. Behaves identically. |
| reject | Returns all elements that do NOT match the condition as an array. The opposite of select. |
Sample Code
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Find the first even number.
first_even = numbers.find { |n| n.even? }
puts first_even # 2
# Returns nil if no match is found.
large_number = numbers.find { |n| n > 100 }
puts large_number.nil? # true
# Get all even numbers.
even_numbers = numbers.find_all { |n| n.even? }
puts even_numbers.inspect # [2, 4, 6, 8, 10]
# Filter an array of hashes by a condition.
users = [
{ name: "Tanaka", age: 25 },
{ name: "Yamada", age: 17 },
{ name: "Suzuki", age: 30 },
{ name: "Sato", age: 15 }
]
# Use reject to exclude users under 18.
adults_only = users.reject { |u| u[:age] < 18 }
puts adults_only.map { |u| u[:name] }.inspect # ["Tanaka", "Suzuki"]
Overview
find and find_all are methods from the Enumerable module, available on any collection such as arrays and hashes. Because find returns only the first matching element, it is well suited for existence checks or fetching a single record.
select is widely used as an alias for find_all and is more commonly seen in real-world code. When you need to exclude non-matching elements, reject lets you express that intent intuitively. Because find returns nil when no match is found, it is recommended to check the return value with nil? or the safe navigation operator &. before using it.
If you find any errors or copyright issues, please contact us.