String#gsub!

str.gsub!(pattern, replacement) -> str or nil
Returns: String or nil · Updated March 13, 2026 · String Methods
strings regex replacement mutation

The gsub! method performs global substitution on a string, replacing all occurrences of a pattern with a replacement string or block result. The bang version modifies the string in place.

Basic Usage

# Simple string replacement
text = "hello world"
text.gsub!("world", "Ruby")
puts text  # => "hello Ruby"

With Regular Expressions

# Regex replacement
text = "abc 123 def 456"
text.gsub!(/\d+/, "NUM")
puts text  # => "abc NUM def NUM"

# Case insensitive
text = "HELLO hello"
text.gsub!(/hello/i, "Hi")
puts text  # => "Hi hello"

With Block

# Block for dynamic replacement
text = "hello world"
text.gsub!(/\w+/) { |word| word.upcase }
puts text  # => "HELLO WORLD"

Return Value

# Returns modified string if changes made
result = "hello".gsub!(/x/, "y")
puts result  # => nil (no changes)

# Returns nil if no changes (bang version)
result = "hello".gsub!("x", "y")
puts result  # => nil

Practical Examples

Redacting Sensitive Data

text = "My phone is 555-1234 and email is test@example.com"
text.gsub!(/\d{3}-\d{4}/, "XXX-XXXX")
text.gsub!(/\S+@\S+\.\S+/, "[EMAIL]")
puts text  # => "My phone is XXX-XXXX and email is [EMAIL]"

Formatting

# Add commas to numbers
text = "1234567"
text.gsub!(/(\d)(?=(\d{3})+(?!\d))/, '\1,')
puts text  # => "1,234,567"

Slug Generation

title = "Hello World! 2024"
slug = title.downcase.gsub!(/[^a-z0-9]+/, '-').gsub!(/^-|-$/, '')
puts slug  # => "hello-world"

Conditional Replacement

text = "one TWO three FOUR"
text.gsub!(/\b[TWO|FOUR]\b/) { |m| m.downcase }
puts text  # => "one two three four"

Comparison with gsub (non-destructive)

# gsub returns new string
original = "hello"
modified = original.gsub("l", "r")
puts original  # => "hello" (unchanged)
puts modified  # => "herro"

# gsub! modifies in place
original = "hello"
original.gsub!("l", "r")
puts original  # => "herro"

Special Replacement Patterns

# \0 or \& - entire match
"hello".gsub("l", "+\0+")  # => "he+l+l+o"

# \1, \2 - capture groups
"john@example.com".gsub(/(\w+)@(\w+)/, '[\1] at \2')  # => "[john] at example"

Performance

For simple string replacements, tr may be faster:

text = "hello"
text.tr!("aeiou", "AEIOU")  # => "hEllO"

See Also