0
0
RubyHow-ToBeginner · 3 min read

How to Use gsub in Ruby: Replace Text Easily

In Ruby, gsub is a method used to replace all occurrences of a pattern in a string with a specified replacement. You call it on a string like string.gsub(pattern, replacement), where pattern can be a string or regular expression, and it returns a new string with replacements.
📐

Syntax

The gsub method replaces all matches of a pattern in a string with a replacement. It does not change the original string but returns a new one.

  • string: The original text you want to change.
  • pattern: What you want to find. It can be a simple string or a regular expression.
  • replacement: The text you want to use instead of the found pattern.
ruby
string.gsub(pattern, replacement)
💻

Example

This example shows how to replace all spaces with dashes in a sentence using gsub. It demonstrates how the method returns a new string with changes but keeps the original string unchanged.

ruby
sentence = "I love ruby programming"
new_sentence = sentence.gsub(" ", "-")
puts new_sentence
puts sentence
Output
I-love-ruby-programming I love ruby programming
⚠️

Common Pitfalls

One common mistake is expecting gsub to change the original string. It returns a new string instead. To change the original string, use gsub! with an exclamation mark.

Another mistake is using a string pattern when a regular expression is needed for more complex matching.

ruby
text = "hello world"
text.gsub("world", "Ruby")
puts text  # prints original text, no change

text.gsub!("world", "Ruby")
puts text  # original text changed
Output
hello world hello Ruby
📊

Quick Reference

UsageDescription
string.gsub(pattern, replacement)Returns new string with all matches replaced
string.gsub!(pattern, replacement)Replaces all matches in original string (in-place)
pattern can be String or RegexpUse Regexp for flexible matching
replacement can be String or blockBlock allows dynamic replacement

Key Takeaways

Use gsub to replace all occurrences of a pattern in a string and get a new string.
gsub does not modify the original string; use gsub! to change it in place.
Patterns can be simple strings or powerful regular expressions.
You can use a block with gsub for custom replacement logic.
Remember gsub returns a new string, so assign or use the result.