How to Use gsub with Regex in Ruby: Simple Guide
In Ruby, you can use
gsub with a regular expression by passing the regex as the first argument and the replacement string as the second. This method searches the string for all matches of the regex and replaces them with the given replacement.Syntax
The gsub method replaces all occurrences of a pattern in a string. When using regex, the pattern is a regular expression object.
string.gsub(/pattern/, 'replacement'): replaces all matches ofpatternwithreplacement.- The
/pattern/is a regex literal in Ruby. - The replacement can be a string or a block for dynamic replacements.
ruby
string = "hello 123 world 456" result = string.gsub(/\d+/, "number") puts result
Output
hello number world number
Example
This example shows how to replace all digits in a string with the word "number" using gsub and a regex.
ruby
text = "My phone is 555-1234 and my zip is 90210." new_text = text.gsub(/\d+/, "[digits]") puts new_text
Output
My phone is [digits]-[digits] and my zip is [digits].
Common Pitfalls
One common mistake is using gsub with a string pattern instead of a regex when you want pattern matching. Also, forgetting to escape special regex characters can cause unexpected results.
Another pitfall is using gsub when you only want to replace the first match; in that case, use sub instead.
ruby
wrong = "abc123".gsub("\d+", "X") # This replaces the literal string "\d+", not digits correct = "abc123".gsub(/\d+/, "X") # This replaces digits correctly puts wrong puts correct
Output
abc123
abcX
Quick Reference
| Usage | Description |
|---|---|
| string.gsub(/pattern/, 'replacement') | Replace all matches of regex pattern with replacement string |
| string.gsub(/pattern/) { |match| block } | Replace matches using a block for dynamic replacement |
| string.sub(/pattern/, 'replacement') | Replace only the first match of regex pattern |
| Escape special chars in regex | Use backslash (\) before special characters like ., *, +, etc. |
Key Takeaways
Use gsub with a regex to replace all matching patterns in a string.
Pass the regex as the first argument and the replacement string or block as the second.
Escape special regex characters to avoid unexpected matches.
Use sub instead of gsub if you want to replace only the first match.
You can use a block with gsub for dynamic replacements based on each match.