How to Use the Ruby scan Method

Contents
In this article, you will learn how to use the Ruby scan method.
Using the scan method
The Ruby scan method is a powerful tool that allows you to extract specific patterns from a string. It returns an array containing all matches of a given regular expression pattern. Here’s how you can use the scan method in your Ruby code:
Syntax
string.scan(pattern)
Parameters
string
: The string to search for matches in.pattern
: The regular expression pattern to match.
Return Value
The scan method returns an array of all matches found in the string.
Example
Extracting All Digits from a String
Suppose you have a string containing a mix of letters and digits, and you want to extract all the digits from it. Here’s how you can use the scan method to do that:
string = "abc123def456"
digits = string.scan(/\d+/)
puts digits.inspect
# Output: ["123", "456"]
In this example, we used the regular expression pattern \d+ to match one or more digits. The scan method found two matches and returned them as an array.
Extracting All Words from a String
Suppose you have a string containing multiple words, and you want to extract all the words from it. Here’s how you can use the scan method to do that:
string = "The quick brown fox jumps over the lazy dog."
words = string.scan(/\w+/)
puts words.inspect
# Output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
In this example, we used the regular expression pattern \w+ to match one or more word characters. The scan method found all the words in the string and returned them as an array.
Extracting All Email Addresses from a String
Suppose you have a string containing multiple email addresses, and you want to extract all the email addresses from it. Here’s how you can use the scan method to do that:
string = "John , Jane "
emails = string.scan(/\w+@\w+\.\w+/)
puts emails.inspect
# Output: ["john@example.com", "jane@example.com"]
In this example, we used the regular expression pattern \w+@\w+\.\w+ to match email addresses. The scan method found all the email addresses in the string and returned them as an array.