0
0
Rubyprogramming~5 mins

Scan for all matches in Ruby

Choose your learning style9 modes available
Introduction

We use scanning to find all parts of a text that match a pattern. It helps us pick out many pieces at once.

You want to find all email addresses in a message.
You need to get all numbers from a string of text.
You want to list all words that start with a capital letter.
You want to extract all hashtags from a tweet.
Syntax
Ruby
string.scan(pattern)  # returns an array of all matches

pattern can be a string or a regular expression.

The result is an array with all matching parts found in the string.

Examples
This finds all groups of digits in the string.
Ruby
"hello 123 world 456".scan(/\d+/)
This finds all words with exactly 6 letters.
Ruby
"apple banana cherry".scan(/\b\w{6}\b/)
This finds all occurrences of the letter 'o'.
Ruby
"one two three".scan("o")
Sample Program

This program finds all email addresses in the text and prints them one by one.

Ruby
text = "My emails are test1@example.com and test2@example.org"
matches = text.scan(/\w+@\w+\.\w+/)
puts "Found emails:"
matches.each { |email| puts email }
OutputSuccess
Important Notes

If no matches are found, scan returns an empty array.

You can use parentheses in your pattern to capture parts of the match.

Summary

scan finds all matches of a pattern in a string.

It returns an array with all matching parts.

Use regular expressions to find complex patterns easily.