Challenge - 5 Problems
Ruby Regex Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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]
Attempts:
2 left
💡 Hint
Remember that the first capture group is accessed with index 1.
✗ Incorrect
The regex captures the word after 'Hello '. The match method returns a MatchData object. Accessing result[1] returns the first captured group, which is 'World'.
❓ Predict Output
intermediate2:00remaining
MatchData object methods
What does this Ruby code print?
Ruby
m = /(\d+)-(\d+)/.match("123-456") puts m.begin(1)
Attempts:
2 left
💡 Hint
begin(n) returns the start index of the nth capture group.
✗ Incorrect
The first capture group (\d+) matches '123' starting at index 0. The second capture group matches '456' starting at index 4. So m.begin(1) returns 0, m.begin(2) returns 4. The code prints 0.
❓ Predict Output
advanced2: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]Attempts:
2 left
💡 Hint
Named captures can be accessed with symbols.
✗ Incorrect
The regex defines named groups 'area' and 'number'. Accessing match[:area] returns the string matched by the 'area' group, which is '555'.
❓ Predict Output
advanced2:00remaining
Match method returns nil when no match
What is the output of this Ruby code?
Ruby
result = /cat/.match("dog") puts result.nil?
Attempts:
2 left
💡 Hint
If the pattern does not match, match returns nil.
✗ Incorrect
The string 'dog' does not contain 'cat', so match returns nil. puts result.nil? prints true.
🧠 Conceptual
expert3: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")
Attempts:
2 left
💡 Hint
match[0] is the entire matched string; match[1] and match[2] are capture groups.
✗ Incorrect
match[0] returns the full matched string 'code-123'. match[1] returns the first capture group '\w+' which is 'code'. match[2] returns the second capture group '\d+' which is '123'.