Recall & Review
beginner
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?<br>
text = "Name: Alice"
if text =~ /Name: (?<user>\w+)/
puts "User is #{Regexp.last_match[:user]}"
endIt 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?
✗ 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'?
✗ Incorrect
You access named captures using square brackets with the name as a symbol or string, like
match[:id].What will this code print?<br>
text = "Age: 30" if text =~ /Age: (?<age>\d+)/ puts Regexp.last_match[:age] end
✗ Incorrect
The named capture 'age' matches '30', so it prints '30'.
Why might you prefer named captures over numbered captures?
✗ 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?
✗ 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.