We use gsub with regex to find and replace patterns in text easily.
Gsub with regex in Ruby
Introduction
Syntax
Ruby
string.gsub(/pattern/, 'replacement')
The /pattern/ is a regular expression that matches parts of the string.
gsub replaces all matches, not just the first one.
Examples
Ruby
"hello 123".gsub(/\d/, '*')
Ruby
"apple banana apple".gsub(/apple/, 'orange')
Ruby
"abc123xyz".gsub(/[a-z]/, '')
Sample Program
This program replaces all phone numbers in the text with "[phone]".
Ruby
text = "Call me at 123-456-7890 or 987-654-3210." cleaned = text.gsub(/\d{3}-\d{3}-\d{4}/, "[phone]") puts cleaned
Important Notes
Regex patterns let you match complex text shapes, not just fixed words.
Remember to escape special characters in regex if you want to match them literally.
gsub returns a new string; it does not change the original string unless you use gsub!.
Summary
gsub with regex helps replace all matching parts in a string.
It is useful for cleaning, formatting, or censoring text.
Always test your regex to make sure it matches what you want.
Practice
1. What does the Ruby method
gsub do when used with a regular expression?easy
Solution
Step 1: Understand
Thegsubpurposegsubmethod is used to replace parts of a string that match a pattern.Step 2: Recognize regex usage
When used with a regex, it finds all matches and replaces them with the given replacement string.Final Answer:
It replaces all parts of the string that match the regex with a specified replacement. -> Option BQuick Check:
gsubwith regex = replace all matches [OK]
Hint: Remember: gsub replaces all regex matches in the string [OK]
Common Mistakes:
- Thinking gsub deletes the string
- Confusing gsub with split
- Assuming gsub returns string length
2. Which of the following is the correct syntax to replace all digits in a string with "#" using
gsub and regex in Ruby?easy
Solution
Step 1: Identify regex syntax in Ruby
Regex patterns in Ruby are enclosed in slashes, like/pattern/.Step 2: Match digits correctly
The regex/\d/matches any digit character. Using it withgsubreplaces all digits.Final Answer:
string.gsub(/\d/, "#") -> Option CQuick Check:
Regex in slashes + \d for digits = string.gsub(/\d/, "#") [OK]
Hint: Use slashes / / for regex, not quotes " " [OK]
Common Mistakes:
- Using quotes instead of slashes for regex
- Using wrong regex like /d/ instead of /\d/
- Not escaping backslash properly
3. What is the output of this Ruby code?
text = "Call me at 123-456-7890." result = text.gsub(/\d/, "*") puts result
medium
Solution
Step 1: Understand the regex and replacement
The regex/\d/matches every digit character. The replacement is "*".Step 2: Apply
Every digit in the string is replaced by "*", so numbers become stars but other characters stay the same.gsubto replace digitsFinal Answer:
Call me at ***-***-****. -> Option AQuick Check:
Digits replaced by * = Call me at ***-***-****. [OK]
Hint: Digits \d replaced by * everywhere in string [OK]
Common Mistakes:
- Expecting only first digit replaced
- Confusing regex syntax causing error
- Thinking gsub changes non-digit characters
4. Identify the error in this Ruby code snippet:
sentence = "Hello World!" sentence.gsub(/world/, "Earth")What is the problem?
medium
Solution
Step 1: Check regex matching
The regex/world/is lowercase and Ruby regex is case-sensitive by default.Step 2: Compare with string content
The string has "World" with uppercase W, so the regex does not match anything.Final Answer:
Regex is case-sensitive, so 'world' does not match 'World'. -> Option AQuick Check:
Case sensitivity causes no match [OK]
Hint: Remember regex is case-sensitive unless flagged [OK]
Common Mistakes:
- Assuming regex matches ignore case by default
- Thinking gsub needs parentheses around arguments
- Believing gsub can't use regex
5. Given the string
data = "User: John_Doe, Email: john@example.com", which gsub call will replace all non-alphanumeric characters (except underscore) with a dash "-"?hard
Solution
Step 1: Understand character classes
\wmatches letters, digits, and underscore.\Wmatches anything not in\w.Step 2: Analyze options
data.gsub(/[^a-zA-Z0-9_]/, "-"):/[^a-zA-Z0-9_]/matches non-alphanumeric except underscore - correct. data.gsub(/\w/, "-"):/\w/replaces word chars (alnum + _) - wrong. data.gsub(/[^a-zA-Z0-9]/, "-"):/[^a-zA-Z0-9]/replaces non-alnum including _ - wrong. data.gsub(/[\w]/, "-"):/[\w]/replaces word chars - wrong.Final Answer:
data.gsub(/[^a-zA-Z0-9_]/, "-") -> Option DQuick Check:
Explicit negated class for alphanumeric + underscore = data.gsub(/[^a-zA-Z0-9_]/, "-") [OK]
Hint: Use negated class [^a-zA-Z0-9_] to keep underscore [OK]
Common Mistakes:
- Using /[^a-zA-Z0-9]/ which replaces underscores too
- Replacing word chars instead of non-word chars
- Confusing \w and \W meaning
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
