Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Pathname#mkpath
() -> self
mkpath(mode: nil) → self
pathname_builtin.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/pathname_builtin.rb, line 466
def mkpath(mode: nil)
path = @path == '/' ? @path : @path.chomp('/')
stack = []
until File.directory?(path) || (parent = File.dirname(path)) == path
stack.push path
path = parent
end
stack.reverse_each do |dir|
dir = dir == '/' ? dir : dir.chomp('/')
if mode
Dir.mkdir dir, mode
File.chmod mode, dir
else
Dir.mkdir dir
end
rescue SystemCallError
raise unless File.directory?(dir)
end
self
end
Creates a directory at the path in self; creates intermediate directories as needed:
Example
pn = Pathname('foo/bar/baz') pn.directory? # => false pn.mkpath # Creates directories 'foo', 'foo/bar', 'foo/bar/baz'. pn.directory? # => true pn.rmtree # Clean up.
When mode is given, directories are created with those permissions; see File Permissions. The permissions for already-existing directories are not changed.