Bird
0
0

How can you replace all digits in a string with '#' but only if the digit is odd, using Ruby's gsub method?

hard📝 Application Q9 of 15
Ruby - String Operations
How can you replace all digits in a string with '#' but only if the digit is odd, using Ruby's gsub method?
Astring.gsub(/[0-9]/, '#')
Bstring.gsub(/[02468]/, '#')
Cstring.gsub(/[13579]/, '#')
Dstring.sub(/[13579]/, '#')
Step-by-Step Solution
Solution:
  1. Step 1: Identify pattern for odd digits

    The regex /[13579]/ matches all odd digits.
  2. Step 2: Use gsub to replace all matches

    Using gsub with this pattern replaces every odd digit with '#'.
  3. Step 3: Check other options

    string.gsub(/[0-9]/, '#') replaces all digits; string.gsub(/[02468]/, '#') matches even digits; string.sub(/[13579]/, '#') uses sub (only first match).
  4. Final Answer:

    string.gsub(/[13579]/, '#') -> Option C
  5. Quick Check:

    gsub with odd digit regex = D [OK]
Quick Trick: Use regex with gsub to target specific characters [OK]
Common Mistakes:
  • Using sub instead of gsub for all replacements
  • Using wrong regex for odd digits
  • Replacing all digits instead of only odd ones

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes