basename(...)
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
/*
* call-seq:
* File.basename(file_name [, suffix] ) -> base_name
*
* Returns the last component of the filename given in <i>file_name</i>,
* which must be formed using forward slashes (``<code>/</code>'')
* regardless of the separator used on the local file system. If
* <i>suffix</i> is given and present at the end of <i>file_name</i>,
* it is removed.
*
* File.basename("/home/gumby/work/ruby.rb")
* File.basename("/home/gumby/work/ruby.rb", ".rb")
*/
static VALUE
rb_file_s_basename(argc, argv)
int argc;
VALUE *argv;
{
VALUE fname, fext, basename;
char *name, *p;
#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
char *root;
#endif
int f, n;
if (rb_scan_args(argc, argv, "11", &fname, &fext) == 2) {
StringValue(fext);
}
StringValue(fname);
if (RSTRING(fname)->len == 0 || !*(name = RSTRING(fname)->ptr))
return 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 fname;
}
basename = rb_str_new(p, f);
OBJ_INFECT(basename, fname);
return basename;
}