Bird
0
0

How can you use Ruby regex to replace all sequences of whitespace with a single space in a string?

hard📝 Application Q9 of 15
Ruby - Regular Expressions
How can you use Ruby regex to replace all sequences of whitespace with a single space in a string?
Atext.scan(/\s+/, ' ')
Btext.match(/\s+/, ' ')
Ctext.gsub(/\s+/, ' ')
Dtext.split(/\s+/, ' ')
Step-by-Step Solution
Solution:
  1. Step 1: Identify regex for whitespace sequences

    The pattern \s+ matches one or more whitespace characters.
  2. Step 2: Use gsub to replace matches

    gsub replaces all occurrences of the pattern with the given string, here a single space.
  3. Final Answer:

    text.gsub(/\s+/, ' ') -> Option C
  4. Quick Check:

    Use gsub with regex to replace patterns [OK]
Quick Trick: Use gsub(/\s+/, ' ') to normalize whitespace [OK]
Common Mistakes:
  • Using scan or match for replacement
  • Using split incorrectly with replacement
  • Not using + quantifier in regex

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes