Challenge - 5 Problems
Ruby Capture Groups Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of capture groups in Ruby regex
What is the output of this Ruby code snippet?
Ruby
text = "Name: John, Age: 30" match = /Name: (\w+), Age: (\d+)/.match(text) puts match[1] puts match[2]
Attempts:
2 left
💡 Hint
Remember that capture groups are accessed by their index starting at 1.
✗ Incorrect
The regex captures the word after 'Name: ' as group 1 and the digits after 'Age: ' as group 2. match[1] returns 'John' and match[2] returns '30'.
❓ Predict Output
intermediate2:00remaining
Using named capture groups in Ruby
What will this Ruby code print?
Ruby
text = "Product: Book, Price: 15" regex = /Product: (?<product>\w+), Price: (?<price>\d+)/ match = regex.match(text) puts match[:product] puts match[:price]
Attempts:
2 left
💡 Hint
Named capture groups can be accessed by symbol keys.
✗ Incorrect
The named groups 'product' and 'price' capture 'Book' and '15' respectively. Accessing match[:product] and match[:price] prints these values.
❓ Predict Output
advanced2:00remaining
Accessing a capture group index beyond available groups
What does this Ruby code print?
Ruby
text = "Date: 2024-06-15" match = /Date: (\d{4})-(\d{2})-(\d{2})/.match(text) p match[4]
Attempts:
2 left
💡 Hint
Check how many capture groups are in the regex and the index used.
✗ Incorrect
The regex has 3 capture groups, so match[4] returns nil. `p nil` prints 'nil'.
🧠 Conceptual
advanced2:00remaining
Effect of non-capturing groups on match data
Given the regex /a(?:b)c(d)/ applied to the string "abcd", how many capture groups does the match have?
Attempts:
2 left
💡 Hint
Non-capturing groups do not count as capture groups.
✗ Incorrect
The (?:b) is a non-capturing group, so only (d) counts as a capture group, total 1.
❓ Predict Output
expert3:00remaining
Output of nested capture groups in Ruby
What is the output of this Ruby code?
Ruby
text = "abc123xyz" regex = /(a(b(c)))(\d+)(x(y)z)/ match = regex.match(text) puts match[0] puts match[1] puts match[2] puts match[3] puts match[4] puts match[5] puts match[6]
Attempts:
2 left
💡 Hint
Nested capture groups are numbered from left to right by their opening parenthesis.
✗ Incorrect
The groups are: 0=full match, 1=(a(b(c))), 2=(b(c)), 3=(c), 4=(\d+), 5=(x(y)z), 6=(y). The output prints each group accordingly.