How to create directories recursively in ruby?

后端 未结 6 2013
醉酒成梦
醉酒成梦 2020-12-02 13:54

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?

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 14:46

    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.

提交回复
热议问题