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.basename

(::path file_name, ?::string suffix) -> ::String
File.basename(path, suffix = '') → string

Returns a new string containing all or part of the last component of the given path. Components are delimited by the value of constant File::SEPARATOR and, if non-nil, the value of constant File::ALT_SEPARATOR.

When suffix is the empty string '', returns all of the last entry:

Example
File.basename('foo/bar/baz/bat.txt') # => "bat.txt"
File.basename('foo/bar/baz')         # => "baz"

File::SEPARATOR                      # => "/"
File.basename('foo/bar.txt////')     # => "bar.txt"
File::ALT_SEPARATOR                  # => "\\"  # On Windows.
File.basename('foo/bar.txt//\\\\//') # => "bar.txt"

When suffix is '.*', the last filename extension, if any, is removed:

Example
File.basename('foo/bar.txt', '.*')     # => "bar"
File.basename('foo/bar.txt.old', '.*') # => "bar.txt"
File.basename('foo/bar', '.*')         # => "bar"

When suffix is any string other than '' or '.*', the matching trailing substring, if any, is removed:

Example
File.basename('foo/bar.txt', '.txt') # => "bar"
File.basename('foo/bar.txt', 'txt')  # => "bar."
File.basename('foo/bar.txt', '*')    # => "bar.txt"
File.basename('foo/bar.txt', '.')    # => "bar.txt"
See also .atime .birthtime .absolute_path? .blockdev? also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0