0
0
Rubyprogramming~5 mins

Find/detect for first match in Ruby

Choose your learning style9 modes available
Introduction

We use find or detect to quickly get the first item in a list that matches what we want. It saves time by stopping as soon as it finds a match.

Looking for the first person in a list who is older than 18.
Finding the first word in a sentence that starts with a capital letter.
Getting the first number in an array that is even.
Searching for the first file in a folder with a specific extension.
Syntax
Ruby
collection.find { |item| condition }
# or
collection.detect { |item| condition }

Both find and detect do the same thing in Ruby.

The block inside { } tells Ruby what condition to check for each item.

Examples
This finds the first even number in the list and prints it.
Ruby
numbers = [1, 3, 5, 8, 10]
even = numbers.find { |n| n.even? }
puts even
This finds the first word containing the letter 'a' and prints it.
Ruby
words = ['apple', 'banana', 'cherry']
word_with_a = words.detect { |w| w.include?('a') }
puts word_with_a
Sample Program

This program looks through a list of people and finds the first one who is 18 or older. Then it prints that person's name.

Ruby
people = [
  { name: 'Alice', age: 17 },
  { name: 'Bob', age: 20 },
  { name: 'Carol', age: 15 }
]
adult = people.find { |person| person[:age] >= 18 }
puts "First adult: #{adult[:name]}"
OutputSuccess
Important Notes

If no item matches, find returns nil.

You can use find with arrays, hashes, or any collection that supports iteration.

Summary

find and detect help you get the first matching item from a list.

They stop searching as soon as they find a match, making your code faster.

Use a block to tell Ruby what to look for in each item.