Bird
0
0

Identify the error in this Ruby code snippet using named captures:

medium📝 Debug Q6 of 15
Ruby - Regular Expressions
Identify the error in this Ruby code snippet using named captures:
text = "Code: 42"
regex = /Code: (?\d+)/
match = regex.match(text)
puts match[:code]
AUsing regex.match instead of text.match
BNo error, code works correctly
CRegex pattern missing escape characters
DAccessing named capture with symbol instead of string
Step-by-Step Solution
Solution:
  1. Step 1: Understand match method

    In Ruby, String#match is used to match regex against a string, returning MatchData.
  2. Step 2: Check usage

    The code calls regex.match(text), but Regexp#match expects a string argument, so this is valid but less common.
  3. Step 3: Verify output

    Actually, Regexp#match with string argument works, so no error here.
  4. Step 4: Re-examine options

    Using regex.match instead of text.match says using regex.match is an error, but it's valid. Accessing named capture with symbol instead of string is wrong because symbol keys are correct. Regex pattern missing escape characters is wrong; pattern is correct. No error, code works correctly says no error.
  5. Final Answer:

    No error, code works correctly -> Option B
  6. Quick Check:

    Regexp#match(string) is valid [OK]
Quick Trick: Regexp#match(string) and String#match(regex) both work [OK]
Common Mistakes:
  • Assuming regex.match(text) is invalid
  • Using string keys instead of symbols for named captures
  • Misunderstanding method call context

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes