Array#find
arr.find { |element| block } -> obj or nil Returns:
Object or nil · Updated March 13, 2026 · Array Methods arrays enumerable search iteration
.find iterates through an array or enumerable and returns the first element for which the block evaluates to truthy. If no element matches, it returns nil. This method is essential for searching collections when you need the actual element rather than its index or position.
Syntax
array.find { |element| block } -> obj or nil
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
block | Proc | Required | A block that receives each element and returns truthy for matching elements |
Examples
Basic usage
numbers = [1, 3, 5, 7, 9]
numbers.find { |n| n > 4 }
# => 5
numbers.find { |n| n > 10 }
# => nil
Finding a hash in an array
users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
]
users.find { |user| user[:age] > 28 }
# => { name: "Alice", age: 30 }
Using with strings
words = ["apple", "banana", "cherry", "date"]
words.find { |word| word.start_with?("b") }
# => "banana"
words.find { |word| word.length > 10 }
# => nil
Common Patterns
Finding by attribute
products = [
{ id: 1, name: "Widget", price: 100 },
{ id: 2, name: "Gadget", price: 50 },
{ id: 3, name: "Gizmo", price: 75 }
]
# Find product by ID
products.find { |p| p[:id] == 2 }
# => { id: 2, name: "Gadget", price: 50 }
Safe navigation with find
results = []
found = results.find { |x| x > 5 }
# Returns nil safely, no error
# Common pattern: use || with default value
found = results.find { |x| x > 5 } || "no match"
# => "no match"
Chaining with other enumerable methods
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# First even number
numbers.select(&:even?).find { |n| n > 5 }
# => 6