Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Pathname#sub

(::Regexp | ::string pattern, ::string | ::Hash[::String, ::String] replacement) -> ::Pathname
(::Regexp | ::string pattern) { (::String match) -> ::string } -> ::Pathname
sub(pattern, replacement) → new_pathname
sub(pattern) {|match| ... } → new_pathname

Returns a new pathname whose path is the path in self, after the specified substitutions.

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 related examples (using strings, not pathnames), see Substitution Methods.

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

Example
pn = Pathname('abracadabra.txt') # => #<Pathname:abracadabra.txt>
pn.sub('bra', 'xyzzy')           # => #<Pathname:axyzzycadabra.txt>
pn.sub(/bra/, 'xyzzy')           # => #<Pathname:axyzzycadabra.txt>
pn.sub('nope', 'xyzzy')          # => #<Pathname:abracadabra.txt>

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'}
pn.sub('b', h) # => #<Pathname:aBracadabra.txt>
pn.sub(/b/, h) # => #<Pathname:aBracadabra.txt>
pn.sub(/d/, h) # => #<Pathname:abracaabra.txt>  # 'd' removed.

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

Example
pn.sub('b') {|match| match.upcase } # => #<Pathname:aBracadabra.txt>
pn.sub(/X/) {|match| match.upcase } # => #<Pathname:abracadabra.txt>
See also #sticky? #sub_ext #stat #symlink? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0