Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directories recursively in ruby?

Tags:

ruby

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?

like image 699
Jan Avatar asked Sep 10 '10 15:09

Jan


People also ask

How do you create a directory in ruby?

Using Ruby's Mkdir Method To Create A New Directory If you want to create a new folder with Ruby you can use the Dir. mkdir method. If given a relative path, this directory is created under the current path ( Dir. pwd ).

How do I change directory in Ruby?

chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.


2 Answers

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

like image 164
Harmon Wood Avatar answered Oct 12 '22 14:10

Harmon Wood


Use mkdir_p to create directory recursively

path = "/tmp/a/b/c"  FileUtils.mkdir_p(path) unless File.exists?(path) 
like image 42
ferbass Avatar answered Oct 12 '22 16:10

ferbass