0
0
Rubyprogramming~10 mins

Match method and MatchData in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Match method and MatchData
Call str.match(pattern)
Search for pattern in str
Return MatchData
Use MatchData to access captures or positions
The match method searches a string for a pattern. If found, it returns a MatchData object with details; if not, it returns nil.
Execution Sample
Ruby
text = "hello123"
result = text.match(/(\w+)(\d+)/)
puts result[0]
puts result[1]
puts result[2]
This code matches letters followed by digits in a string and prints the full match and captured groups.
Execution Table
StepActionEvaluationResult
1Call text.match(/(\w+)(\d+)/)Search 'hello123' for patternMatch found: 'hello123'
2Access result[0]Full matched string'hello123'
3Access result[1]First capture group (\w+)'hello'
4Access result[2]Second capture group (\d+)'123'
5If no matchReturns nilnil (not reached here)
💡 Pattern found in string, so MatchData returned and used to access captures.
Variable Tracker
VariableStartAfter matchAfter accessing capturesFinal
text"hello123""hello123""hello123""hello123"
resultnilMatchData object for 'hello123'Same MatchDataSame MatchData
Key Moments - 2 Insights
Why does result[0] give the full matched string, not just the first capture?
Because in MatchData, index 0 always holds the entire matched substring, while indexes 1 and up hold capture groups (see execution_table rows 2 and 3).
What happens if the pattern is not found in the string?
The match method returns nil, so trying to access result[0] would cause an error. This is shown in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does result[1] contain at step 3?
AThe first capture group 'hello'
BThe full matched string 'hello123'
CThe second capture group '123'
Dnil
💡 Hint
Check execution_table row 3 where result[1] is accessed.
At which step does the match method confirm no match was found?
AStep 3
BStep 5
CStep 1
DStep 2
💡 Hint
Look at execution_table row 5 describing no match case.
If the string was 'abc' and pattern /(\d+)/ was used, what would result be?
AMatchData with 'abc'
BMatchData with digits
Cnil
DError
💡 Hint
Refer to key_moments about no match returning nil.
Concept Snapshot
match(pattern) searches a string for a pattern.
Returns MatchData if found, else nil.
MatchData[0] is full match.
MatchData[1..] are capture groups.
Check for nil before accessing captures.
Full Transcript
The Ruby match method looks for a pattern inside a string. If it finds the pattern, it returns a MatchData object. This object holds the full matched text at index 0 and any captured groups at indexes 1 and beyond. If the pattern is not found, match returns nil. You can access parts of the match using result[0], result[1], etc. Always check if the result is nil before accessing captures to avoid errors.