0
0
RubyComparisonBeginner · 3 min read

Gsub vs Sub in Ruby: Key Differences and When to Use Each

In Ruby, sub replaces only the first occurrence of a pattern in a string, while gsub replaces all occurrences. Both methods return a new string with replacements and do not modify the original string unless used with !.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of sub and gsub methods in Ruby.

Featuresubgsub
Replacement scopeReplaces first occurrence onlyReplaces all occurrences
ReturnsNew string with first match replacedNew string with all matches replaced
Modifies original string?No, unless sub! is usedNo, unless gsub! is used
Use caseChange one matchChange every match
PerformanceFaster for single replacementSlightly slower for multiple replacements
⚖️

Key Differences

The main difference between sub and gsub lies in how many matches they replace in a string. sub changes only the first occurrence of the pattern it finds, making it useful when you want to replace just one instance.

On the other hand, gsub replaces every occurrence of the pattern throughout the entire string. This is helpful when you want to update all matches at once.

Both methods return a new string with the replacements and do not change the original string unless you use their bang versions (sub! or gsub!), which modify the string in place.

⚖️

Code Comparison

Using sub to replace the first occurrence of 'cat' with 'dog' in a string:

ruby
text = "cat bat cat"
result = text.sub("cat", "dog")
puts result
Output
dog bat cat
↔️

gsub Equivalent

Using gsub to replace all occurrences of 'cat' with 'dog' in the same string:

ruby
text = "cat bat cat"
result = text.gsub("cat", "dog")
puts result
Output
dog bat dog
🎯

When to Use Which

Choose sub when you want to replace only the first match in a string, such as changing a single word or token. Choose gsub when you need to replace every match, like cleaning up all instances of a word or pattern.

For example, use sub to fix the first typo in a sentence, and use gsub to remove all unwanted characters from a text.

Key Takeaways

sub replaces only the first occurrence of a pattern in a string.
gsub replaces all occurrences of a pattern throughout the string.
Both return a new string and do not modify the original unless using sub! or gsub!.
Use sub for single replacements and gsub for global replacements.
sub is slightly faster for one replacement; gsub is better for multiple.