Bird
0
0

Why does the match operator =~ return nil when the pattern is not found in the string?

hard📝 Conceptual Q10 of 15
Ruby - Regular Expressions
Why does the match operator =~ return nil when the pattern is not found in the string?
ABecause no match means no index to return
BBecause it always returns nil regardless
CBecause it throws an error internally
DBecause it returns false instead of nil
Step-by-Step Solution
Solution:
  1. Step 1: Understand match operator return values

    It returns the index of the first match if found.
  2. Step 2: Reason about no match case

    If no match exists, there is no index to return, so it returns nil.
  3. Final Answer:

    Because no match means no index to return -> Option A
  4. Quick Check:

    No match returns nil, not error or false [OK]
Quick Trick: No match means no index, so returns nil [OK]
Common Mistakes:
  • Thinking it returns false instead of nil
  • Expecting an error on no match
  • Assuming it always returns a number

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes