Skip to content
instance method

String#gsub

(::Regexp | ::string pattern, ::string | ::hash[::String, ::_ToS] replacement) -> ::String
(::Regexp | ::string pattern) -> ::Enumerator[::String, ::String]
(::Regexp | ::string pattern) { (::String match) -> ::_ToS } -> ::String
gsub(pattern, replacement) → new_string
gsub(pattern) {|match| ... } → new_string
gsub(pattern) → enumerator

Returns a copy of self with zero or more substrings replaced.

Argument pattern may be a string or a Regexp; argument replacement may be a string or a Hash. Varying types for the argument values makes this method very versatile.

Below are some simple examples; for many more examples, see Substitution Methods.

With arguments pattern and string replacement given, replaces each matching substring with the given replacement string:

Example
s = 'abracadabra'
s.gsub('ab', 'AB')   # => "ABracadABra"
s.gsub(/[a-c]/, 'X') # => "XXrXXXdXXrX"

With arguments pattern and hash replacement given, replaces each matching substring with a value from the given replacement hash, or removes it:

Example
h = {'a' => 'A', 'b' => 'B', 'c' => 'C'}
s.gsub(/[a-c]/, h) # => "ABrACAdABrA"  # 'a', 'b', 'c' replaced.
s.gsub(/[a-d]/, h) # => "ABrACAABrA"   # 'd' removed.

With argument pattern and a block given, calls the block with each matching substring; replaces that substring with the block’s return value:

Example
s.gsub(/[a-d]/) {|substring| substring.upcase }
# => "ABrACADABrA"

With argument pattern and no block given, returns a new Enumerator.

Related: see Converting to New String.

Ruby version changes

  1. 3.0
See also #gsub! #grapheme_clusters #getbyte #hash also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0