Challenge - 5 Problems
Ruby Named Captures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of named capture groups in Ruby regex
What is the output of this Ruby code using named captures?
Ruby
text = "Name: Alice, Age: 30" pattern = /Name: (?<name>\w+), Age: (?<age>\d+)/ m = text.match(pattern) puts "Name is #{m[:name]} and age is #{m[:age]}"
Attempts:
2 left
💡 Hint
Look at how named captures are accessed using the match object with symbols.
✗ Incorrect
The regex uses named captures 'name' and 'age'. The match object allows access to these captures by their names as symbols, so m[:name] returns 'Alice' and m[:age] returns '30'.
❓ Predict Output
intermediate2:00remaining
Accessing named captures with MatchData#named_captures
What does this Ruby code print?
Ruby
text = "Product: Book, Price: 15" pattern = /Product: (?<product>\w+), Price: (?<price>\d+)/ m = text.match(pattern) p m.named_captures
Attempts:
2 left
💡 Hint
named_captures returns a hash with string keys and string values.
✗ Incorrect
The named_captures method returns a hash where keys are strings of the capture names and values are the matched strings. So it returns {"product"=>"Book", "price"=>"15"}.
🔧 Debug
advanced2:00remaining
Identify the error in named capture usage
What error does this Ruby code raise?
Ruby
text = "User: John" pattern = /User: (?<username>\w+)/ m = text.match(pattern) puts m[:user]
Attempts:
2 left
💡 Hint
Check if the named capture key used matches the regex group name.
✗ Incorrect
The named capture group is 'username', but the code tries to access m[:user]. This key does not exist, so Ruby raises a KeyError.
❓ Predict Output
advanced2:00remaining
Using named captures with multiple matches
What is the output of this Ruby code?
Ruby
text = "a1 b2 c3" pattern = /(?<letter>\w)(?<digit>\d)/ text.scan(pattern) do |letter, digit| puts "Letter: #{letter}, Digit: #{digit}" end
Attempts:
2 left
💡 Hint
scan returns all matches and yields captures as block parameters.
✗ Incorrect
The pattern matches pairs of letter and digit. scan yields each pair to the block, printing each letter and digit on separate lines.
🧠 Conceptual
expert2:00remaining
Behavior of named captures with optional groups
Given this Ruby code, what is the value of m[:middle] after matching?
Ruby
text = "John Smith" pattern = /(?<first>\w+) (?: (?<middle>\w+) )? (?<last>\w+)/x m = text.match(pattern) m[:middle].inspect
Attempts:
2 left
💡 Hint
Optional named capture groups return nil if not matched.
✗ Incorrect
The middle name group is optional and not present in the text. So m[:middle] returns nil.