How to Use the Ruby match Method

Contents
In this article, you will learn how to use the Ruby match method.
Using the match method
The match method in Ruby is a powerful method that allows you to search for a specific pattern within a string and extract any matching portions of the string.
The basic syntax for the match method is as follows:
string.match(pattern)
Here, string
is the string you want to search, and pattern
is the regular expression pattern you want to match against the string.
For example, let’s say we have a string str = “The quick brown fox jumps over the lazy dog.”, and we want to search for the word “brown” in this string. We can use the match method as follows:
match_data = str.match(/brown/)
In this example, we used a regular expression pattern /brown/ to match against the string. The match method returns a MatchData object that contains information about the match. We assigned this object to the variable match_data.
We can now use various methods on the MatchData object to get information about the match. For example, we can use the to_s method to get the actual string that matched the pattern:
matched_string = match_data.to_s
puts matched_string #=> "brown"
We can also use the pre_match and post_match methods to get the portions of the string that appeared before and after the matched substring:
before_string = match_data.pre_match
puts before_string #=> "The quick "
after_string = match_data.post_match
puts after_string #=> " fox jumps over the lazy dog."
If the regular expression pattern contains groups (enclosed in parentheses), we can use the [] operator on the MatchData object to get the portions of the string that matched each group:
str = "John Doe,123 Main St.,Anytown,USA"
match_data = str.match(/(\w+) (\w+),(\d+) (\w+\.),(\w+)/)
puts match_data[0] #=> "John Doe,123 Main St.,Anytown,USA"
puts match_data[1] #=> "John"
puts match_data[2] #=> "Doe"
puts match_data[3] #=> "123"
puts match_data[4] #=> "Main St."
puts match_data[5] #=> "Anytown"
puts match_data[6] #=> "USA"
In this example, we used a regular expression pattern with six groups to match against the string. We then used the [] operator on the MatchData object to get the portions of the string that matched each group.