Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Pathname#basename

(?::String | ::_ToStr suffix) -> ::Pathname
basename(path, suffix = '') → new_pathname

Returns a new Pathname object containing all or part of the last entry of the path represented by self. Entries 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
Pathname.new('foo/bar/baz/bat.txt').basename # => #<Pathname:bat.txt>
Pathname.new('foo/bar/baz').basename         # => #<Pathname:baz>

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

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

Example
Pathname.new('foo/bar.txt').basename('.*')     # => #<Pathname:bar>
Pathname.new('foo/bar.txt.old').basename('.*') # => #<Pathname:bar.txt>
Pathname.new('foo/bar').basename('.*')         # => #<Pathname:bar>

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

Example
Pathname.new('foo/bar.txt').basename('.txt') # => #<Pathname:bar>
Pathname.new('foo/bar.txt').basename('txt')  # => #<Pathname:bar.>
Pathname.new('foo/bar.txt').basename('*')    # => #<Pathname:bar.txt>
Pathname.new('foo/bar.txt').basename('.')    # => #<Pathname:bar.txt>
See also #atime #binread #ascend #binwrite also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0