Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Pathname#sub
static VALUE
path_sub(int argc, VALUE *argv, VALUE self)
{
VALUE str = get_strpath(self);
if (rb_block_given_p()) {
str = rb_block_call(str, id_sub, argc, argv, 0, 0);
}
else {
str = rb_funcallv(str, id_sub, argc, argv);
}
return rb_class_new_instance(1, &str, rb_obj_class(self));
}
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:
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:
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:
pn.sub('b') {|match| match.upcase } # => #<Pathname:aBracadabra.txt> pn.sub(/X/) {|match| match.upcase } # => #<Pathname:abracadabra.txt>