Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Pathname#sub_ext
(::string replacement) -> ::Pathname
sub_ext(replacement) → new_pathname
pathname.c
View on GitHub ↗
static VALUE
path_sub_ext(VALUE self, VALUE repl)
{
VALUE path = get_strpath(self);
rb_len_t len = RSTRING_LEN(path);
const char *ptr = RSTRING_PTR(path);
const char *ext = ruby_enc_find_extname(ptr, &len, rb_enc_get(path));
if (len > 0) {
RUBY_ASSERT(ext, "should point the last dot");
path = rb_str_subseq(path, 0, ext - ptr);
}
else {
/* no dot or dotted file */
path = rb_str_dup(path);
}
path = rb_str_append(path, repl);
return rb_class_new_instance(1, &path, rb_obj_class(self));
}
Returns a new pathname whose path is the path in self, after specified changes:
Example
Pathname('t.tmp').sub_ext('.txt') # => #<Pathname:t.txt> # Extension replaced. Pathname('temp').sub_ext('.txt') # => #<Pathname:temp.txt> # Extension added. Pathname('t.tmp').sub_ext('') # => #<Pathname:t> # Extension removed.