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.
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 ).
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.
You are probably trying to create nested directories. Assuming foo
does not exist, you will receive no such file or directory
error for:
Dir.mkdir 'foo/bar'
# => Errno::ENOENT: No such file or directory - 'foo/bar'
To create nested directories at once, FileUtils
is needed:
require 'fileutils'
FileUtils.mkdir_p 'foo/bar'
# => ["foo/bar"]
Edit2: you do not have to use FileUtils
, you may do system call (update from @mu is too short comment):
> system 'mkdir', '-p', 'foo/bar' # worse version: system 'mkdir -p "foo/bar"'
=> true
But that seems (at least to me) as worse approach as you are using external 'tool' which may be unavailable on some systems (although I can hardly imagine system without mkdir
, but who knows).
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
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