basename (p1, p2 = v2)
public
Returns the last component of the filename given in file_name,
which must be formed using forward slashes (“/”) regardless of the
separator used on the local file system. If suffix is given and
present at the end of file_name, it is removed.
File . basename (" /home/gumby/work/ruby.rb ")
File . basename (" /home/gumby/work/ruby.rb ", " .rb ")
Show source static VALUE
rb_file_s_basename(int argc, VALUE *argv)
{
VALUE fname, fext, basename;
const char *name, *p;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
const char *root;
#endif
int f, n;
if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
StringValue(fext);
}
FilePathStringValue(fname);
if (RSTRING_LEN(fname) == 0 || !*(name = RSTRING_PTR(fname)))
return rb_str_new_shared(fname);
name = skipprefix(name);
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
root = name;
#endif
while (isdirsep(*name))
name++;
if (!*name) {
p = name - 1;
f = 1;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
if (name != root) {
/* has slashes */
}
#ifdef DOSISH_DRIVE_LETTER
else if (*p == ':') {
p++;
f = 0;
}
#endif
#ifdef DOSISH_UNC
else {
p = "/";
}
#endif
#endif
}
else {
if (!(p = strrdirsep(name))) {
p = name;
}
else {
while (isdirsep(*p)) p++; /* skip last / */
}
#if USE_NTFS
n = ntfs_tail(p) - p;
#else
n = chompdirsep(p) - p;
#endif
if (NIL_P(fext) || !(f = rmext(p, n, StringValueCStr(fext)))) {
f = n;
}
if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
}
basename = rb_str_new(p, f);
rb_enc_copy(basename, fname);
OBJ_INFECT(basename, fname);
return basename;
} 1Note File.dirname provides what File.basename omits.