Create Directory if it doesn't exist with Ruby
RubyRuby Problem Overview
I am trying to create a directory with the following code:
Dir.mkdir("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
unless File.exists?("/Users/Luigi/Desktop/Survey_Final/Archived/Survey/test")
However, I'm receiving this error:
>No such file or directory - /Users/Luigi/Desktop/Survey_Final/Archived/Survey/test (Errno::ENOENT)
Why is this directory not being created by the Dir.mkdir
statement above?
Ruby Solutions
Solution 1 - Ruby
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).
Solution 2 - Ruby
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
Solution 3 - Ruby
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
Solution 4 - Ruby
How about just Dir.mkdir('dir') rescue nil
?