Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
File.basename
(::path file_name, ?::string suffix) -> ::String
File.basename(path, suffix = '') → string
file.c
View on GitHub ↗
static VALUE
rb_file_s_basename(int argc, VALUE *argv, VALUE _)
{
VALUE fname, fext = Qnil;
const char *name, *p, *fp = 0;
rb_len_t f = 0, n;
rb_encoding *enc;
argc = rb_check_arity(argc, 1, 2);
fname = argv[0];
CheckPath(fname, name);
if (argc == 2) {
fext = argv[1];
fp = StringValueCStr(fext);
check_path_encoding(fext);
}
if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
enc = rb_str_enc_get(fname);
}
n = RSTRING_LEN(fname);
if (n <= 0 || !*name) {
return rb_enc_str_new(0, 0, enc);
}
bool mb_enc = enc_mbclen_needed(enc);
p = enc_find_basename(name, &f, &n, mb_enc, enc);
if (n >= 0) {
if (!fp) {
f = n;
}
else {
if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
f = n;
}
RB_GC_GUARD(fext);
}
if (f == RSTRING_LEN(fname)) {
return rb_str_new_shared(fname);
}
}
return rb_enc_str_new(p, f, enc);
}
Returns a new string containing all or part of the last component of the given path. Components are delimited by the value of constant File::SEPARATOR and, if non-nil, the value of constant File::ALT_SEPARATOR.
When suffix is the empty string '', returns all of the last entry:
Example
File.basename('foo/bar/baz/bat.txt') # => "bat.txt" File.basename('foo/bar/baz') # => "baz" File::SEPARATOR # => "/" File.basename('foo/bar.txt////') # => "bar.txt" File::ALT_SEPARATOR # => "\\" # On Windows. File.basename('foo/bar.txt//\\\\//') # => "bar.txt"
When suffix is '.*', the last filename extension, if any, is removed:
Example
File.basename('foo/bar.txt', '.*') # => "bar" File.basename('foo/bar.txt.old', '.*') # => "bar.txt" File.basename('foo/bar', '.*') # => "bar"
When suffix is any string other than '' or '.*', the matching trailing substring, if any, is removed:
Example
File.basename('foo/bar.txt', '.txt') # => "bar" File.basename('foo/bar.txt', 'txt') # => "bar." File.basename('foo/bar.txt', '*') # => "bar.txt" File.basename('foo/bar.txt', '.') # => "bar.txt"