如何在 Ruby 中递归地创建目录?

我想将一个文件存储为/a/b/c/d.txt,但是我不知道是否存在这些目录,如果需要,还需要递归地创建它们。 用红宝石怎么能做到呢?

43208 次浏览
 require 'ftools'

File.makedirs

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'.

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`

Use mkdir_p to create directory recursively

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


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

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.

Pathname to the rescue!

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