0
0
RubyHow-ToBeginner · 3 min read

How to Use find Method in Ruby: Syntax and Examples

In Ruby, use the find method to get the first element in a collection that meets a condition specified in a block. It returns the element if found, or nil if no match exists.
📐

Syntax

The find method is called on an enumerable like an array. You provide a block with a condition inside { } or do...end. It returns the first element for which the block returns true.

  • receiver: The array or enumerable you want to search.
  • block: A condition to test each element.
  • return: The first matching element or nil if none match.
ruby
collection.find { |element| condition }
💻

Example

This example shows how to find the first number greater than 10 in an array.

ruby
numbers = [5, 8, 12, 20, 3]
result = numbers.find { |num| num > 10 }
puts result
Output
12
⚠️

Common Pitfalls

One common mistake is forgetting to provide a block, which causes an error. Another is expecting find to return all matching elements; it only returns the first match. Use select to get all matches.

ruby
numbers = [1, 2, 3, 4, 5]

# Wrong: no block given
# numbers.find

# Wrong: expecting all matches
first_greater_than_two = numbers.find { |n| n > 2 }
puts first_greater_than_two # Outputs only 3

# Right: use select for all matches
all_greater_than_two = numbers.select { |n| n > 2 }
puts all_greater_than_two.join(", ")
Output
3 3, 4, 5
📊

Quick Reference

  • find: Returns first element matching condition or nil.
  • select: Returns all elements matching condition as an array.
  • Always provide a block with a condition.
  • Works on arrays, hashes, and other enumerables.

Key Takeaways

Use find to get the first element matching a condition in a collection.
Always provide a block with a condition when using find.
find returns nil if no element matches the condition.
To get all matching elements, use select instead of find.
find works on arrays and other enumerable objects.