Bird
0
0

Why does the following code delete all occurrences of digits instead of leaving the string unchanged?

hard📝 Conceptual Q10 of 15
Ruby - Regular Expressions
Why does the following code delete all occurrences of digits instead of leaving the string unchanged?
str = "a1b2c3"
str.gsub(/\d/) { |match| match if str.count("0-9") == 1 }
ABecause the block returns nil for all digits, so all digits are replaced with empty string
BBecause gsub replaces only last match by default
CBecause regex /\d/ matches only last digit
DBecause block syntax is invalid and causes error
Step-by-Step Solution
Solution:
  1. Step 1: Understand block behavior in gsub

    The block returns the replacement only if the count of digits is 1, else returns nil.
  2. Step 2: Analyze digit count during iteration

    Since str.count("0-9") is always 3, the block returns nil for all matches.
  3. Final Answer:

    Because the block returns nil for all digits, so all digits are replaced with empty string -> Option A
  4. Quick Check:

    Block return nil = empty replacement [OK]
Quick Trick: Block return nil replaces with empty string in gsub [OK]
Common Mistakes:
  • Thinking gsub replaces only last match by default
  • Assuming regex matches only last digit
  • Believing block syntax causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes