Bird
Raised Fist0
Rubyprogramming~10 mins

Gsub with regex in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Gsub with regex
Start with original string
↓
Apply gsub with regex
↓
Match regex pattern in string?
No→Return modified string
Yes↓
Replace matched part
↓
Continue to next match
↩Back to Match regex pattern
The program starts with a string, applies gsub with a regex to find matches, replaces each match, and continues until no matches remain, then returns the new string.
Execution Sample
Ruby
text = "hello 123 world 456"
new_text = text.gsub(/\d+/, "#")
puts new_text
This code replaces all groups of digits in the string with the '#' character.
Execution Table
StepCurrent StringRegex MatchReplacementResulting String
1hello 123 world 456/\d+/"#"hello # world 456
2hello # world 456/\d+/"#"hello # world #
3hello # world #/\d+/nonehello # world #
💡 No more regex matches found, gsub returns the final modified string.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
text"hello 123 world 456""hello 123 world 456""hello 123 world 456""hello 123 world 456"
new_textnil"hello # world 456""hello # world #""hello # world #"
Key Moments - 3 Insights
Why does gsub replace all matches, not just the first one?
Because gsub scans the entire string for all matches of the regex, replacing each one, as shown in execution_table steps 1 and 2.
What happens if the regex does not match anything in the string?
gsub returns the original string unchanged, as shown in execution_table step 3 where no match is found.
Why is the original string 'text' unchanged after gsub?
Because gsub returns a new string with replacements; it does not modify the original string in place.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of new_text after step 2?
A"hello # world 456"
B"hello # world #"
C"hello 123 world 456"
D"hello world 456"
💡 Hint
Check the 'Resulting String' column in row for step 2.
At which step does gsub find no more matches?
AStep 3
BStep 2
CStep 1
DNever
💡 Hint
Look at the 'Regex Match' column where it says 'none'.
If the regex was changed to /world/, what would be the first replacement?
A"hello # 123 # 456"
B"654 # 321 # olleh"
C"hello 123 # 456"
Dhello # 123 # 456"
💡 Hint
Consider that only the word 'world' would be replaced with '#', not digits.
Concept Snapshot
gsub with regex:
- Syntax: string.gsub(/pattern/, replacement)
- Finds all matches of regex pattern in string
- Replaces each match with replacement
- Returns new string, original unchanged
- Useful for replacing patterns like digits, words, etc.
Full Transcript
This visual execution shows how Ruby's gsub method works with a regex pattern. Starting with the string 'hello 123 world 456', gsub searches for all digit groups using /\d+/. At step 1, it finds '123' and replaces it with '#', resulting in 'hello # world 456'. At step 2, it finds '456' and replaces it with '#', resulting in 'hello # world #'. At step 3, no more matches are found, so gsub returns the final string. The original string remains unchanged. This helps beginners see how gsub scans and replaces all matches step-by-step.

Practice

(1/5)
1. What does the Ruby method gsub do when used with a regular expression?
easy
A. It returns the length of the string.
B. It replaces all parts of the string that match the regex with a specified replacement.
C. It deletes the string entirely.
D. It splits the string into an array based on the regex.

Solution

  1. Step 1: Understand gsub purpose

    The gsub method is used to replace parts of a string that match a pattern.
  2. Step 2: Recognize regex usage

    When used with a regex, it finds all matches and replaces them with the given replacement string.
  3. Final Answer:

    It replaces all parts of the string that match the regex with a specified replacement. -> Option B
  4. Quick Check:

    gsub with 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
A. string.gsub("\d", "#")
B. string.gsub(/d/, "#")
C. string.gsub(/\d/, "#")
D. string.gsub("[0-9]", "#")

Solution

  1. Step 1: Identify regex syntax in Ruby

    Regex patterns in Ruby are enclosed in slashes, like /pattern/.
  2. Step 2: Match digits correctly

    The regex /\d/ matches any digit character. Using it with gsub replaces all digits.
  3. Final Answer:

    string.gsub(/\d/, "#") -> Option C
  4. Quick 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
A. Call me at ***-***-****.
B. Call me at 123-456-7890.
C. Call me at \d\d\d-\d\d\d-\d\d\d\d.
D. SyntaxError

Solution

  1. Step 1: Understand the regex and replacement

    The regex /\d/ matches every digit character. The replacement is "*".
  2. Step 2: Apply gsub to replace digits

    Every digit in the string is replaced by "*", so numbers become stars but other characters stay the same.
  3. Final Answer:

    Call me at ***-***-****. -> Option A
  4. Quick 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
A. Regex is case-sensitive, so 'world' does not match 'World'.
B. Missing replacement string in gsub.
C. Syntax error due to missing parentheses.
D. gsub cannot be used with regex.

Solution

  1. Step 1: Check regex matching

    The regex /world/ is lowercase and Ruby regex is case-sensitive by default.
  2. Step 2: Compare with string content

    The string has "World" with uppercase W, so the regex does not match anything.
  3. Final Answer:

    Regex is case-sensitive, so 'world' does not match 'World'. -> Option A
  4. Quick 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
A. data.gsub(/[\w]/, "-")
B. data.gsub(/\w/, "-")
C. data.gsub(/[^a-zA-Z0-9]/, "-")
D. data.gsub(/[^a-zA-Z0-9_]/, "-")

Solution

  1. Step 1: Understand character classes

    \w matches letters, digits, and underscore. \W matches anything not in \w.
  2. 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.
  3. Final Answer:

    data.gsub(/[^a-zA-Z0-9_]/, "-") -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard