Skip to content
instance method

String#sub

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

Returns a copy of self, possibly with a substring 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 the first matching substring with the given replacement string:

Example
s = 'abracadabra'       # => "abracadabra"
s.sub('bra', 'xyzzy')   # => "axyzzycadabra"
s.sub(/bra/, 'xyzzy')   # => "axyzzycadabra"
s.sub('nope', 'xyzzy')  # => "abracadabra"

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

Example
h = {'a' => 'A', 'b' => 'B', 'c' => 'C'}
s.sub('b', h)  # => "aBracadabra"
s.sub(/b/, h)  # => "aBracadabra"
s.sub(/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.sub('b') {|match| match.upcase } # => "aBracadabra"

Related: see Converting to New String.

Ruby version changes

  1. 3.0
See also #sub! #strip! #strip #succ also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0