0
0
Rubyprogramming~20 mins

Named captures in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Named Captures Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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]}"
AName is and age is 30
BName is and age is
CName is Alice and age is
DName is Alice and age is 30
Attempts:
2 left
💡 Hint
Look at how named captures are accessed using the match object with symbols.
Predict Output
intermediate
2: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
A{"product"=>15, "price"=>"Book"}
B{:product=>"Book", :price=>"15"}
C{"product"=>"Book", "price"=>"15"}
Dnil
Attempts:
2 left
💡 Hint
named_captures returns a hash with string keys and string values.
🔧 Debug
advanced
2: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]
AKeyError
BNoMethodError
Cnil
DSyntaxError
Attempts:
2 left
💡 Hint
Check if the named capture key used matches the regex group name.
Predict Output
advanced
2: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
A
Letter: a, Digit: 1
Letter: b, Digit: 2
Letter: c, Digit: 3
B
Letter: a1, Digit: b2
Letter: c3, Digit: 
CSyntaxError
D
Letter: a, Digit: 1
Letter: b, Digit: 2
Attempts:
2 left
💡 Hint
scan returns all matches and yields captures as block parameters.
🧠 Conceptual
expert
2: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
A"John"
Bnil
C"Smith"
D" "
Attempts:
2 left
💡 Hint
Optional named capture groups return nil if not matched.