How do I create directory if none exists using File class in Ruby?

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

For those looking for a way to create a directory if it doesn't exist, here's the simple solution:

require 'fileutils'

FileUtils.mkdir_p 'dir_name'

Based on Eureka's comment.


You can use FileUtils to recursively create parent directories, if they are not already present:

require 'fileutils'

dirname = File.dirname(some_path)
unless File.directory?(dirname)
  FileUtils.mkdir_p(dirname)
end

Edit: Here is a solution using the core libraries only (reimplementing the wheel, not recommended)

dirname = File.dirname(some_path)
tokens = dirname.split(/[\/\\]/) # don't forget the backslash for Windows! And to escape both "\" and "/"

1.upto(tokens.size) do |n|
  dir = tokens[0...n]
  Dir.mkdir(dir) unless Dir.exist?(dir)
end

Tags:

Ruby