static public Method

File.basename(...)

File.basename(file_name [, suffix] )  base_name

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")          #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

Source Code

/*
*  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")          #=> "ruby.rb"
*     File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
*/

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;

   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))) {
       if (NIL_P(fext) || !(f = rmext(name, StringValueCStr(fext)))) {
           f = chompdirsep(name) - name;
           if (f == RSTRING(fname)->len) return fname;
       }
       p = name;
   }
   else {
       while (isdirsep(*p)) p++; /* skip last / */
       if (NIL_P(fext) || !(f = rmext(p, StringValueCStr(fext)))) {
           f = chompdirsep(p) - p;
       }
   }
   basename = rb_str_new(p, f);
   OBJ_INFECT(basename, fname);
   return basename;
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.