What is a named capture in Ruby regular expressions?
A named capture lets you give a name to a part of a regular expression match, so you can access it by that name instead of by number.
Click to reveal answer
beginner
How do you define a named capture group in a Ruby regex?
Use the syntax (?<name>pattern) where name is the capture's name and pattern is what you want to match.
Click to reveal answer
beginner
How do you access the value of a named capture after a match in Ruby?
You can use MatchData#[] with the capture name as a symbol or string, like match[:name] or match["name"].
Click to reveal answer
beginner
What does this Ruby code output?
text = "Name: Alice"
if text =~ /Name: (?<user>\w+)/
puts "User is #{Regexp.last_match[:user]}"
end
It outputs: User is Alice because the named capture user matches "Alice" and is accessed with Regexp.last_match[:user].
Click to reveal answer
beginner
Why are named captures useful compared to numbered captures?
Named captures make code easier to read and maintain because you use meaningful names instead of numbers, which can be confusing especially with many groups.
Click to reveal answer
Which syntax defines a named capture group in Ruby regex?
A(name:pattern)
B(?<name>pattern)
C(name=pattern)
D(pattern?<name>)
✗ Incorrect
The correct syntax for named captures in Ruby is (?pattern).
How do you access a named capture called 'id' from a MatchData object named 'match'?
Amatch.id
Bmatch.get('id')
Cmatch['id']()
Dmatch[:id]
✗ Incorrect
You access named captures using square brackets with the name as a symbol or string, like match[:id].
What will this code print?
text = "Age: 30"
if text =~ /Age: (?<age>\d+)/
puts Regexp.last_match[:age]
end
Aage
BAge
C30
DError
✗ Incorrect
The named capture 'age' matches '30', so it prints '30'.
Why might you prefer named captures over numbered captures?
AThey make code easier to understand by using meaningful names.
BThey run faster than numbered captures.
CThey allow matching multiple patterns at once.
DThey automatically convert strings to numbers.
✗ Incorrect
Named captures improve readability by using descriptive names instead of numbers.
Which of the following provides access to the MatchData object after a successful regex match in Ruby?
AAll of the above
BRegexp.last_match
CString#match
D=~ operator
✗ Incorrect
All these can provide MatchData: =~ operator sets Regexp.last_match, and String#match returns MatchData.
Explain how to create and use named captures in Ruby regular expressions.
Think about the <code>(?<name>pattern)</code> syntax and accessing with MatchData.
You got /3 concepts.
Describe the benefits of using named captures instead of numbered captures in Ruby regex.
Consider how meaningful names help when you have many groups.
You got /3 concepts.
Practice
(1/5)
1. What does a named capture group in Ruby regex do? /(?<name>pattern)/
easy
A. Repeats the pattern multiple times
B. Makes the regex case-insensitive
C. Labels a part of the matched text with a name for easy access
D. Matches only digits in the text
Solution
Step 1: Understand named capture syntax
The syntax ?<name> inside parentheses names the capture group.
Step 2: Purpose of named captures
This lets you access matched parts by name instead of number, making code clearer.
Final Answer:
Labels a part of the matched text with a name for easy access -> Option C
Quick Check:
Named capture = label matched text [OK]
Hint: Named captures label groups for easy access by name [OK]
Common Mistakes:
Confusing named captures with regex flags
Thinking named captures repeat patterns
Assuming named captures only match digits
2. Which of the following is the correct syntax for a named capture group in Ruby regex?
easy
A. /<year>\d{4}/
B. /(?year>\d{4})/
C. /(?/
D. /(?<year>\d{4})/
Solution
Step 1: Recall named capture syntax
Named captures use ?<name> inside parentheses to name the group.
Step 2: Check each option
/(?<year>\d{4})/ correctly uses (?<year>\d{4}). Others miss brackets or have wrong syntax.
Final Answer:
/(?<year>\d{4})/ is correct syntax -> Option D
Quick Check:
Correct syntax = (?<name>) [OK]
Hint: Look for parentheses with ?<name> inside [OK]
Common Mistakes:
Omitting angle brackets around the name
Placing name outside parentheses
Using wrong brackets or missing parentheses
3. What is the output of this Ruby code?
text = "Date: 2024-06-15"
regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
m = text.match(regex)
puts "Year: #{m[:year]}, Month: #{m[:month]}, Day: #{m[:day]}"
medium
A. Year: 2024, Month: 06, Day: 15
B. Year: , Month: , Day:
C. Year: 2024-06-15, Month: 2024-06-15, Day: 2024-06-15
D. Error: undefined method [] for nil
Solution
Step 1: Match regex with named captures
The regex captures year, month, and day parts from the text "Date: 2024-06-15".
Step 2: Access named captures from match object
Using m[:year], m[:month], and m[:day] returns "2024", "06", and "15" respectively.
Final Answer:
Year: 2024, Month: 06, Day: 15 -> Option A
Quick Check:
Named captures return parts by name [OK]
Hint: Use m[:name] to get named capture values [OK]
Common Mistakes:
Using m['name'] instead of m[:name]
Forgetting to call match before accessing captures
Expecting full match instead of named parts
4. Find the error in this Ruby code using named captures:
text = "User: alice, Age: 30"
regex = /User: (?<name>\w+), Age: (?<age>\d+)/
m = regex.match(text)
puts "Name: #{m['name']}, Age: #{m['age']}"
medium
A. Regex pattern missing parentheses
B. Using string keys instead of symbols to access named captures
C. Match method called on regex instead of string
D. No error, code runs fine
Solution
Step 1: Check how named captures are accessed
Named captures in Ruby match objects are accessed with symbols, like m[:name], not strings.
Step 2: Identify the error in code
The code uses m['name'] and m['age'], which causes a nil result or error.
Final Answer:
Using string keys instead of symbols to access named captures -> Option B
Quick Check:
Use symbols, not strings, for named captures [OK]
Hint: Access named captures with symbols like m[:name] [OK]
Common Mistakes:
Using string keys instead of symbols
Confusing match method call on regex vs string
Missing parentheses in regex groups
5. Given this text:
"Order #1234: 5 items, total $99.95"
Write a Ruby regex with named captures to extract order number, item count, and total price. Which regex correctly captures these parts?
hard
A. /Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{2})/
B. /Order #(?<order_num>\d+), (?<items>\d+) items total \$(?<total>\d+\.\d{2})/
C. /Order #(?<order_num>\d+): (?<items>\d+) items total \$(?<total>\d+\.\d{2})/
D. /Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{3})/
Solution
Step 1: Analyze the text format
The text is "Order #1234: 5 items, total $99.95" with colon and comma exactly as shown.
Step 2: Match regex parts carefully
/Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{2})/ matches colon after order number, space, number of items, comma, space, "total $", and price with two decimals.
Step 3: Check other options
Options A and C miss the comma or colon or both, and /Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{3})/ expects three decimals instead of two.
Final Answer:
/Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{2})/ -> Option A
Quick Check:
Match exact punctuation and decimal places [OK]
Hint: Match exact punctuation and decimal digits in regex [OK]
Common Mistakes:
Missing colon or comma in pattern
Wrong decimal places in price capture
Using incorrect group names or syntax
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.