Array#detect

arr.detect { |element| block } -> obj or nil
Returns: Object or nil · Updated March 13, 2026 · Array Methods
arrays enumerable search iteration

.detect is an alias for .find. It 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.

Syntax

array.detect { |element| block } -> obj or nil

Parameters

ParameterTypeDefaultDescription
blockProcRequiredA block that receives each element and returns truthy for matching elements

Examples

Basic usage

numbers = [1, 3, 5, 7, 9]

numbers.detect { |n| n > 4 }
# => 5

numbers.detect { |n| n > 10 }
# => nil

Finding a hash in an array

users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
]

users.detect { |user| user[:age] > 28 }
# => { name: "Alice", age: 30 }

Using with strings

words = ["apple", "banana", "cherry", "date"]

words.detect { |word| word.start_with?("b") }
# => "banana"

words.detect { |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.detect { |p| p[:id] == 2 }
# => { id: 2, name: "Gadget", price: 50 }

Safe navigation with detect

results = []

found = results.detect { |x| x > 5 }
# Returns nil safely, no error

# Common pattern: use || with default value
found = results.detect { |x| x > 5 } || "no match"
# => "no match"

See Also