0
0
Rubyprogramming~5 mins

Match method and MatchData in Ruby

Choose your learning style9 modes available
Introduction

The match method helps find patterns in text. It returns a MatchData object that holds details about the found pattern.

You want to check if a word or pattern exists in a sentence.
You need to extract parts of a string that match a pattern, like dates or emails.
You want to find where a pattern starts and ends in a string.
Syntax
Ruby
string.match(pattern)  # returns MatchData or nil

pattern is usually a regular expression (regex).

If the pattern is found, match returns a MatchData object; otherwise, it returns nil.

Examples
Finds the word 'world' in the string. Returns a MatchData object.
Ruby
"hello world".match(/world/)
Finds the first 3 digits in the string.
Ruby
"123-456".match(/\d{3}/)
Pattern not found, returns nil.
Ruby
"abc".match(/xyz/)
Sample Program

This program looks for a phone number pattern in the text. If found, it prints the number and where it starts.

Ruby
text = "My phone number is 555-1234."
result = text.match(/\d{3}-\d{4}/)
if result
  puts "Found phone number: #{result[0]}"
  puts "Starts at index: #{result.begin(0)}"
else
  puts "No phone number found."
end
OutputSuccess
Important Notes

You can access matched parts using result[0] for the whole match or result[n] for groups.

MatchData has useful methods like begin and end to find match positions.

Summary

The match method finds patterns in strings and returns a MatchData object if found.

MatchData holds details about the match, like the matched text and its position.

If no match is found, match returns nil.