Bird
0
0

Which of the following is the correct syntax to replace all whitespace characters in a string with underscores using gsub and regex?

easy📝 Syntax Q3 of 15
Ruby - Regular Expressions
Which of the following is the correct syntax to replace all whitespace characters in a string with underscores using gsub and regex?
Astr.gsub("\s", "_")
Bstr.gsub(" ", "_")
Cstr.gsub(/ /, "_")
Dstr.gsub(/\s/, "_")
Step-by-Step Solution
Solution:
  1. Step 1: Understand regex for whitespace

    The regex /\s/ matches any whitespace character including spaces.
  2. Step 2: Use gsub with regex pattern

    Syntax requires regex delimiters // around the pattern.
  3. Final Answer:

    str.gsub(/\s/, "_") -> Option D
  4. Quick Check:

    Replace spaces with underscores using /\s/ regex [OK]
Quick Trick: Use /\s/ to match any whitespace in regex [OK]
Common Mistakes:
  • Using string instead of regex for pattern
  • Missing regex delimiters //
  • Using escaped string instead of regex

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes