Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
File.extname
(::path path) -> ::String
File.extname(path) → extension
file.c
View on GitHub ↗
static VALUE
rb_file_s_extname(VALUE klass, VALUE fname)
{
const char *name;
CheckPath(fname, name);
rb_len_t len = RSTRING_LEN(fname);
if (len < 1) {
return rb_enc_str_new(0, 0, rb_str_enc_get(fname));
}
bool mb_enc = !rb_str_enc_fastpath(fname);
rb_encoding *enc = rb_str_enc_get(fname);
const char *ext = enc_find_extname(name, &len, mb_enc, enc);
return rb_enc_str_new(ext, len, enc);
}
Returns the filename extension – usually the portion of the string path beginning from the last period:
Example
File.extname('t.rb') # => ".rb" File.extname('foo.bar.t.rb') # => ".rb" File.extname('foo/bar/t.rb') # => ".rb" File.extname('nosuch.txt') # => ".txt" # Path need not exist.
Returns the entire string when there is no period:
Example
Pathname('foo').extname # => ""
Returns an empty string when the only period is the first character:
Example
File.extname('.irbrc') # => ""
Returns an empty string or '.' when path ends with a period:
Example
File.extname('foo.') # => "" # On Windows. File.extname('foo.') # => "." # Elsewhere. File.extname('foo....') # => "" # On Windows. File.extname('foo....') # => "." # Elsewhere.