Gsub vs Sub in Ruby: Key Differences and When to Use Each
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.
| Feature | sub | gsub |
|---|---|---|
| Replacement scope | Replaces first occurrence only | Replaces all occurrences |
| Returns | New string with first match replaced | New string with all matches replaced |
| Modifies original string? | No, unless sub! is used | No, unless gsub! is used |
| Use case | Change one match | Change every match |
| Performance | Faster for single replacement | Slightly 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:
text = "cat bat cat" result = text.sub("cat", "dog") puts result
gsub Equivalent
Using gsub to replace all occurrences of 'cat' with 'dog' in the same string:
text = "cat bat cat" result = text.gsub("cat", "dog") puts result
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.sub! or gsub!.sub for single replacements and gsub for global replacements.sub is slightly faster for one replacement; gsub is better for multiple.