Bird
Raised Fist0
Rubyprogramming~10 mins

Named captures in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Named captures
Define regex with named captures
↓
Apply regex to string
↓
Match found?
No→Exit: No match
Yes↓
Extract named groups
↓
Use captured values
The program defines a regex with named groups, applies it to a string, checks for a match, and extracts the named captures for use.
Execution Sample
Ruby
text = "Name: Alice, Age: 30"
regex = /Name: (?<name>\w+), Age: (?<age>\d+)/
match = regex.match(text)
puts match[:name]
puts match[:age]
This code extracts the name and age from a string using named captures in a regex.
Execution Table
StepActionEvaluationResult
1Define text stringtext = "Name: Alice, Age: 30"text holds the string
2Define regex with named captures/Name: (?<name>\w+), Age: (?<age>\d+)/regex holds pattern with 'name' and 'age' groups
3Apply regex.match(text)regex.match(text)match object with captures if matched
4Check if match is foundmatch != niltrue (match found)
5Extract match[:name]match[:name]"Alice"
6Extract match[:age]match[:age]"30"
7Print match[:name]puts match[:name]Outputs: Alice
8Print match[:age]puts match[:age]Outputs: 30
💡 Execution ends after printing captured values from named groups.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
textnil"Name: Alice, Age: 30""Name: Alice, Age: 30""Name: Alice, Age: 30""Name: Alice, Age: 30""Name: Alice, Age: 30""Name: Alice, Age: 30"
regexnilnil/Name: (?<name>\w+), Age: (?<age>\d+)//Name: (?<name>\w+), Age: (?<age>\d+)//Name: (?<name>\w+), Age: (?<age>\d+)//Name: (?<name>\w+), Age: (?<age>\d+)//Name: (?<name>\w+), Age: (?<age>\d+)/
matchnilnilnil#<MatchData "Name: Alice, Age: 30" name:"Alice" age:"30">#<MatchData "Name: Alice, Age: 30" name:"Alice" age:"30">#<MatchData "Name: Alice, Age: 30" name:"Alice" age:"30">#<MatchData "Name: Alice, Age: 30" name:"Alice" age:"30">
match[:name]nilnilnilnil"Alice""Alice""Alice"
match[:age]nilnilnilnilnil"30""30"
Key Moments - 2 Insights
Why do we use match[:name] instead of match[1] to get the captured value?
Using match[:name] accesses the captured group by its name, which is clearer and less error-prone than using numeric indexes like match[1]. This is shown in execution_table rows 5 and 6 where named captures are extracted.
What happens if the regex does not match the string?
If no match is found, match will be nil (see execution_table step 4). Trying to access match[:name] would cause an error, so always check if match is not nil before accessing captures.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the value of match[:name]?
A"Alice"
B"30"
Cnil
D"Name"
💡 Hint
Check the 'Result' column at step 5 in the execution_table.
At which step does the program confirm a successful match?
AStep 3
BStep 4
CStep 6
DStep 2
💡 Hint
Look at the 'Action' and 'Evaluation' columns in execution_table to find where match != nil is checked.
If the input string was "Name: Bob, Age: 25", what would match[:age] be at step 6?
A"Alice"
Bnil
C"25"
D"Bob"
💡 Hint
Refer to variable_tracker for match[:age] values and imagine the string changed to "Name: Bob, Age: 25".
Concept Snapshot
Named captures in Ruby regex use syntax (?<name>pattern).
Apply regex.match(string) to get MatchData.
Access groups by name: match[:name].
Check match is not nil before accessing.
Makes code clearer and safer than numeric indexes.
Full Transcript
This example shows how Ruby uses named captures in regular expressions. First, a string with a name and age is defined. Then, a regex with named groups 'name' and 'age' is created. The regex is applied to the string using match. If a match is found, the named captures are extracted using match[:name] and match[:age]. These values are printed. The execution table traces each step, showing variable values and actions. Key points include using named captures for clarity and checking for a match before accessing captures. The visual quiz tests understanding of these steps and values.

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

  1. Step 1: Understand named capture syntax

    The syntax ?<name> inside parentheses names the capture group.
  2. Step 2: Purpose of named captures

    This lets you access matched parts by name instead of number, making code clearer.
  3. Final Answer:

    Labels a part of the matched text with a name for easy access -> Option C
  4. 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

  1. Step 1: Recall named capture syntax

    Named captures use ?<name> inside parentheses to name the group.
  2. Step 2: Check each option

    /(?<year>\d{4})/ correctly uses (?<year>\d{4}). Others miss brackets or have wrong syntax.
  3. Final Answer:

    /(?<year>\d{4})/ is correct syntax -> Option D
  4. 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

  1. Step 1: Match regex with named captures

    The regex captures year, month, and day parts from the text "Date: 2024-06-15".
  2. Step 2: Access named captures from match object

    Using m[:year], m[:month], and m[:day] returns "2024", "06", and "15" respectively.
  3. Final Answer:

    Year: 2024, Month: 06, Day: 15 -> Option A
  4. 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

  1. Step 1: Check how named captures are accessed

    Named captures in Ruby match objects are accessed with symbols, like m[:name], not strings.
  2. Step 2: Identify the error in code

    The code uses m['name'] and m['age'], which causes a nil result or error.
  3. Final Answer:

    Using string keys instead of symbols to access named captures -> Option B
  4. 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

  1. Step 1: Analyze the text format

    The text is "Order #1234: 5 items, total $99.95" with colon and comma exactly as shown.
  2. 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.
  3. 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.
  4. Final Answer:

    /Order #(?<order_num>\d+): (?<items>\d+) items, total \$(?<total>\d+\.\d{2})/ -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard