0
0
Rubyprogramming~5 mins

Named captures in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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]}"
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>)
How do you access a named capture called 'id' from a MatchData object named 'match'?
Amatch.id
Bmatch.get('id')
Cmatch['id']()
Dmatch[:id]
What will this code print?<br>
text = "Age: 30"
if text =~ /Age: (?<age>\d+)/
  puts Regexp.last_match[:age]
end
Aage
BAge
C30
DError
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.
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
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.