How to create directories recursively in ruby?

Ruby

Ruby Problem Overview


I want to store a file as /a/b/c/d.txt, but I do not know if any of these directories exist and need to recursively create them if necessary. How can one do this in ruby?

Ruby Solutions


Solution 1 - Ruby

Use mkdir_p:

FileUtils.mkdir_p '/a/b/c'

The _p is a unix holdover for parent/path you can also use the alias mkpath if that makes more sense for you.

FileUtils.mkpath '/a/b/c'

In Ruby 1.9 FileUtils was removed from the core, so you'll have to require 'fileutils'.

Solution 2 - Ruby

Use mkdir_p to create directory recursively

path = "/tmp/a/b/c"

FileUtils.mkdir_p(path) unless File.exists?(path)

Solution 3 - Ruby

If you are running on unixy machines, don't forget you can always run a shell command under ruby by placing it in backticks.

`mkdir -p /a/b/c`

Solution 4 - Ruby

Pathname to the rescue!

Pathname('/a/b/c/d.txt').dirname.mkpath

Solution 5 - Ruby

 require 'ftools'

File.makedirs

Solution 6 - Ruby

You could also use your own logic

def self.create_dir_if_not_exists(path)
  recursive = path.split('/')
  directory = ''
  recursive.each do |sub_directory|
    directory += sub_directory + '/'
    Dir.mkdir(directory) unless (File.directory? directory)
  end
end

So if path is 'tmp/a/b/c' if 'tmp' doesn't exist 'tmp' gets created, then 'tmp/a/' and so on and so forth.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJanView Question on Stackoverflow
Solution 1 - RubyHarmon WoodView Answer on Stackoverflow
Solution 2 - RubyferbassView Answer on Stackoverflow
Solution 3 - RubyMatthew SchinckelView Answer on Stackoverflow
Solution 4 - RubyVadym TyemirovView Answer on Stackoverflow
Solution 5 - RubyeinarmagnusView Answer on Stackoverflow
Solution 6 - Rubykamal patwaView Answer on Stackoverflow