Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

File.dirname

File.dirname(file_name, level = 1) → dir_name

Returns all components of the filename given in file_name except the last one (after first stripping trailing separators). The filename can be formed using both File::SEPARATOR and File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is not nil.

Example
File.dirname("/home/gumby/work/ruby.rb")   #=> "/home/gumby/work"

If level is given, removes the last level components, not only one.

Example
File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"

Ruby version changes

  1. 3.1
See also .directory? .empty? .delete .executable? also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0