Possible Duplicate:
How to create directories recursively in ruby?
In Ruby, how could I do:
mkdir -p cool/beans
Here's what I came up with:
Dir.mkdir('cool') unless File.directory?('cool') cool_beans_path = File.join('cool', 'beans') Dir.mkdir(cool_beans_path) unless File.directory?(cool_beans_path)
But, isn't there a better way?
I know I could do:
system('mkdir', '-p', File.join('cool', 'beans'))
But, that's not platform independent, is it? Like, it works on Mac but not on Windows, right?
Using Ruby's Mkdir Method To Create A New Directory If you want to create a new folder with Ruby you can use the Dir. mkdir method. If given a relative path, this directory is created under the current path ( Dir. pwd ).
If it matters whether the file you're looking for is a directory and not just a file, you could use File. directory? or Dir. exist? . This will return true only if the file exists and is a directory.
A directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files.
chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.
require 'fileutils' FileUtils.mkdir_p 'cool/beans'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With