0
0
Rubyprogramming~20 mins

Match method and MatchData in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Regex Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Match method with capture groups
What is the output of this Ruby code?
Ruby
result = /Hello (\w+)/.match("Hello World")
puts result[1]
Anil
BHello
CWorld
DError
Attempts:
2 left
💡 Hint
Remember that the first capture group is accessed with index 1.
Predict Output
intermediate
2:00remaining
MatchData object methods
What does this Ruby code print?
Ruby
m = /(\d+)-(\d+)/.match("123-456")
puts m.begin(1)
A0
B4
C3
DError
Attempts:
2 left
💡 Hint
begin(n) returns the start index of the nth capture group.
Predict Output
advanced
2:00remaining
Using MatchData to extract named captures
What is the output of this Ruby code?
Ruby
pattern = /(?<area>\d{3})-(?<number>\d{4})/
match = pattern.match("555-1234")
puts match[:area]
A1234
B555
Carea
Dnil
Attempts:
2 left
💡 Hint
Named captures can be accessed with symbols.
Predict Output
advanced
2:00remaining
Match method returns nil when no match
What is the output of this Ruby code?
Ruby
result = /cat/.match("dog")
puts result.nil?
Atrue
Bnil
Cfalse
DError
Attempts:
2 left
💡 Hint
If the pattern does not match, match returns nil.
🧠 Conceptual
expert
3:00remaining
Understanding MatchData captures and indexing
Given the Ruby code below, what is the value of match[0], match[1], and match[2] respectively?
Ruby
match = /(\w+)-(\d+)/.match("code-123")
A"code", "code-123", "123"
B"code", "-", "123"
C"code-123", "-", "123"
D"code-123", "code", "123"
Attempts:
2 left
💡 Hint
match[0] is the entire matched string; match[1] and match[2] are capture groups.