Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
File.dirname
(::path file_name, ?::Integer level) -> ::String
File.dirname(path, count = 1) → string
file.c
View on GitHub ↗
static VALUE
rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
{
int n = 1;
if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
n = NUM2INT(argv[1]);
}
return rb_file_dirname_n(argv[0], n);
}
Returns a string path containing all but the last count components of the given path:
Example
File.dirname('/usr/lib/linux') # => "/usr/lib" File.dirname('/usr') # => "/" File.dirname('/') # => "/" File.dirname('lib/') # => "." File.dirname('nosuch') # => "." File.dirname('/usr/lib/linux', 2) # => "/usr" File.dirname('/usr/lib/linux', 20) # => "/" File.dirname('/usr/lib/linux', 0) # => "/usr/lib/linux"
Components are delimited by File::SEPARATOR and, if non-nil, File::ALT_SEPARATOR.
Ruby version changes
-
3.1
-
File.dirnamenow accepts an optional argument for the level to strip path components. [Feature #12194]
-