Bird
0
0

What is the issue with this Ruby code snippet?

medium📝 Debug Q6 of 15
Ruby - Regular Expressions
What is the issue with this Ruby code snippet?
text = "abc123"
if text.match(/\d+/)
  puts "Digits found"
else
  puts "No digits"
end
ANo issue; code works correctly to detect digits
BUsing match returns nil or MatchData, so condition always false
CRegex pattern is incorrect; should be /[0-9]+/
DShould use =~ operator instead of match method
Step-by-Step Solution
Solution:
  1. Step 1: Understand match method behavior

    text.match(/\d+/) returns a MatchData object if digits found, else nil.
  2. Step 2: Evaluate if condition

    In Ruby, nil is falsey, MatchData is truthy, so condition works as intended.
  3. Final Answer:

    No issue; code works correctly to detect digits -> Option A
  4. Quick Check:

    match returns truthy MatchData or nil [OK]
Quick Trick: match returns MatchData or nil, usable in if [OK]
Common Mistakes:
  • Assuming match always returns boolean
  • Confusing match with =~ operator
  • Thinking regex pattern is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes