How to Use the Ruby detect Method

09/23/2021

Contents

In this article, you will learn how to use the Ruby detect method.

Using the detect method

The detect method in Ruby (also known as find) is a powerful and flexible way to search through an enumerable object (like an array) and return the first element that matches a specific condition. In this guide, we’ll go over how to use the detect method in Ruby.

Syntax

The syntax for using detect is as follows:

enumerable.detect { |element| block }

Here, enumerable is the object that you want to search through (e.g. an array), and block is a code block that specifies the condition you’re looking for. The block should return true if the element matches the condition, and false otherwise.

Basic Usage

Let’s start with a simple example. Suppose we have an array of numbers:

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

We want to find the first even number in the array. We can use detect like this:

even_number = numbers.detect { |n| n.even? }

This will return 2, since it is the first even number in the array.

If there is no element in the enumerable that matches the condition specified in the block, detect will return nil.

odd_number = numbers.detect { |n| n.odd? }

This will return 1, since it is the first odd number in the array.

Using with a Lambda

Instead of using a block, you can also pass in a lambda (or Proc) to detect. Here’s an example:

is_positive = ->(n) { n > 0 }
positive_number = numbers.detect(&is_positive)

This will return 1, since it is the first positive number in the array.

Using with a Hash

detect can also be used with a hash, by passing in a block that operates on the hash’s key-value pairs. Here’s an example:

prices = { apple: 0.5, banana: 0.25, orange: 0.75 }
expensive_fruit = prices.detect { |fruit, price| price > 0.6 }

This will return [:orange, 0.75], since it is the first key-value pair where the price is greater than 0.6.

Using with Regular Expressions

detect can be used with regular expressions to find the first element that matches a specific pattern. Here’s an example:

words = ["hello", "world", "how", "are", "you"]
long_word = words.detect { |word| /oo/ =~ word }

This will return “good”, since it is the first word in the array that contains the letters “oo”.