Kernel#gsub

str.gsub(pattern, replacement) -> string
Returns: string · Updated March 13, 2026 · Kernel Methods
strings substitution regex pattern-matching

String#gsub (global substitute) replaces all occurrences of a pattern in a string. It returns a new string with every match replaced by the replacement. This method is one of the most powerful and frequently used string manipulation tools in Ruby.

Syntax

str.gsub(pattern, replacement)
str.gsub(pattern) { |match| block }

Parameters

ParameterTypeDefaultDescription
patternString or RegexpThe substring or pattern to find and replace
replacementString, Hash, or nilThe replacement text, hash of substitutions, or nil when using a block

Examples

Basic string replacement

text = "hello world"
text.gsub("world", "Ruby")
# => "hello Ruby"

Replacing all occurrences

text = "hello world hello"
text.gsub("hello", "goodbye")
# => "goodbye world goodbye"

Using regex patterns

phone = "(555) 123-4567"
phone.gsub(/\(\d{3}\)\s*/, "")
# => "123-4567"

text = "one two three"
text.gsub(/\w+/) { |word| word.upcase }
# => "ONE TWO THREE"

Regex patterns unlock the true power of this method. You can match complex patterns, capture groups, and apply transformations conditionally.

Using a hash for multiple replacements

replacements = { "cat" => "dog", "run" => "walk" }
"cat run".gsub(/cat|run/, replacements)
# => "dog walk"

The hash replacement is particularly useful when you need to perform several different substitutions in one pass.

Working with capture groups

"first last".gsub(/(\w+) (\w+)/, '\2, \1')
# => "last, first"

"hello".gsub(/[aeiou]/) { |v| v.upcase }
# => "hEllO"

Common Patterns

  • Find and replace: text.gsub("old", "new")
  • Remove characters: text.gsub(/[^\w]/, "")
  • Normalize whitespace: text.gsub(/\s+/, " ").strip
  • Capture groups: text.gsub(/(\w+) (\w+)/, '\2 \1')
  • Case conversion: text.gsub(/[A-Z]/) { |c| c.downcase }
  • Phone number formatting: phone.gsub(/\D/, '')

Errors

  • No pattern given: Raises ArgumentError if neither pattern nor block is provided.
  • String interpolation in replacement: Remember to escape \1, \2 when using double-quoted strings, or use single quotes.

See Also