0
0
RubyHow-ToBeginner · 3 min read

How to Use detect Method in Ruby: Simple Guide

In Ruby, detect is a method used on collections like arrays to find the first element that meets a condition given in a block. It returns that element or nil if none match. Use it by calling collection.detect { |item| condition }.
📐

Syntax

The detect method is called on an enumerable collection. It takes a block where you specify the condition to find the element.

  • collection.detect { |element| condition }
  • collection: The array or enumerable you want to search.
  • element: Each item in the collection, one by one.
  • condition: A test that returns true or false.

The method returns the first element for which the condition is true, or nil if none match.

ruby
collection.detect { |element| condition }
💻

Example

This example shows how to find the first even number in an array using detect. It returns the first number that is even.

ruby
numbers = [1, 3, 5, 8, 10]
even_number = numbers.detect { |num| num.even? }
puts even_number
Output
8
⚠️

Common Pitfalls

One common mistake is forgetting to provide a block to detect, which will cause an error. Another is expecting detect to return all matching elements, but it only returns the first match. Use select if you want all matches.

ruby
numbers = [1, 3, 5, 8, 10]

# Wrong: no block given
# numbers.detect

# Wrong: expecting all even numbers
all_evens_wrong = numbers.detect { |num| num.even? }
puts all_evens_wrong # Outputs only 8

# Right: use select for all matches
all_evens_right = numbers.select { |num| num.even? }
puts all_evens_right.inspect
Output
8 [8, 10]
📊

Quick Reference

detect finds the first element matching a condition.

  • Returns the element or nil if none found.
  • Use with a block that returns true/false.
  • Use select to get all matching elements.

Key Takeaways

Use detect to find the first element matching a condition in a collection.
Always provide a block with a condition to detect.
detect returns only one element or nil, not all matches.
Use select if you want all elements that match the condition.
If no element matches, detect returns nil.