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
pathname_builtin.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/pathname_builtin.rb, line 2086
def basename(...) self.class.new(File.basename(@path, ...)) end
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>