Skip to content

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

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.
See also .expand_path .file? .exist? .fnmatch also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0