Gsub and sub for replacement in Ruby - Time & Space Complexity
When we use sub or gsub in Ruby, we want to know how the time to replace text grows as the text gets longer.
We ask: How does the work change when the input string grows?
Analyze the time complexity of the following code snippet.
text = "hello hello hello"
result_sub = text.sub("hello", "hi")
result_gsub = text.gsub("hello", "hi")
This code replaces the first occurrence of "hello" with "hi" using sub, and all occurrences using gsub.
Look at what repeats when replacing text:
- Primary operation: Scanning the string to find matches of the target text.
- How many times: For
sub, it stops after the first match; forgsub, it continues scanning the whole string to replace all matches.
As the string gets longer, the time to scan grows roughly with the string length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks for matches |
| 100 | About 100 checks for matches |
| 1000 | About 1000 checks for matches |
Pattern observation: The work grows in a straight line as the string gets longer.
Time Complexity: O(n)
This means the time to replace text grows directly with the length of the string.
[X] Wrong: "gsub is always much slower than sub because it replaces all matches."
[OK] Correct: Both scan the string, but gsub continues scanning after the first match, so the difference depends on how many matches there are, not just the method itself.
Understanding how string replacement scales helps you write efficient code and explain your choices clearly in real projects or interviews.
What if we used a regular expression with gsub instead of a simple string? How would the time complexity change?
Practice
sub and gsub methods in Ruby?Solution
Step 1: Understand
subbehaviorsubreplaces only the first occurrence of the pattern in the string.Step 2: Understand
gsubbehaviorgsubreplaces all occurrences of the pattern in the string.Final Answer:
subreplaces only the first match,gsubreplaces all matches. -> Option BQuick Check:
sub = first match, gsub = all matches [OK]
- Confusing which method replaces all matches
- Thinking sub works on arrays
- Believing gsub replaces only one match
"cat and cat" using sub?Solution
Step 1: Identify correct method for first occurrence replacement
subreplaces only the first match, so it is the correct method here.Step 2: Check method syntax
The syntax isstring.sub(pattern, replacement), so"cat and cat".sub('cat', 'dog')is correct.Final Answer:
"cat and cat".sub('cat', 'dog') -> Option DQuick Check:
sub syntax = string.sub(pattern, replacement) [OK]
- Using gsub instead of sub for first occurrence
- Using non-existent methods like replace or substitute
- Wrong method call syntax
text = "hello hello hello"
result = text.sub('hello', 'hi')
puts resultSolution
Step 1: Understand what
subdoes heresubreplaces only the first occurrence of 'hello' with 'hi'.Step 2: Apply replacement to the string
The first 'hello' becomes 'hi', the rest remain unchanged, so the string becomes "hi hello hello".Final Answer:
hi hello hello -> Option AQuick Check:
sub replaces first match only [OK]
- Thinking sub replaces all matches
- Confusing output with gsub behavior
- Misreading the string content
fruit = "apple banana apple grape"
new_fruit = fruit.sub('apple', 'orange')
puts new_fruitSolution
Step 1: Identify the method used
The code usessub, which replaces only the first match.Step 2: Correct method for replacing all matches
To replace all occurrences,gsubshould be used instead ofsub.Final Answer:
Usegsubinstead ofsubto replace all occurrences. -> Option AQuick Check:
gsub replaces all matches, sub replaces first only [OK]
- Using sub when gsub is needed
- Thinking sub works on arrays
- Believing method names are case sensitive differently
"2023-04-01 and 2023-05-01", you want to replace only the month part (the two digits after the first dash) with '12' for all dates. Which Ruby code correctly does this using gsub and a regex?Solution
Step 1: Identify the pattern to replace
The month is the two digits between dashes, so the regex-(\d{2})-matches the dash, two digits, then dash.Step 2: Use
Usinggsubto replace all matchesgsubwith the pattern and replacement '-12-' replaces the month part in all dates.Final Answer:
"2023-04-01 and 2023-05-01".gsub(/-(\d{2})-/, '-12-') -> Option CQuick Check:
gsub with regex replaces all month parts correctly [OK]
- Using sub instead of gsub for all matches
- Incorrect regex missing dashes
- Replacing wrong parts of the string
Ready to prove it?
Pass the test and this pattern moves unknown
