How to Use the Ruby dir.mkdir Method

09/23/2021

Contents

In this article, you will learn how to use the Ruby dir.mkdir method.

Using the dir.mkdir method

The dir.mkdir method is a built-in method in the Ruby programming language that is used to create a new directory. It is part of the Dir class, which is used for working with directories.

To use the dir.mkdir method, you first need to require the fileutils module, which contains various utility methods for working with files and directories. You can do this using the following code:

require 'fileutils'

Once you have required the fileutils module, you can use the dir.mkdir method to create a new directory. The dir.mkdir method takes a single argument, which is the path to the directory you want to create. The path can be either absolute or relative to the current working directory.

Here’s an example of how to use the dir.mkdir method to create a new directory called “mydir” in the current working directory:

require 'fileutils'

Dir.mkdir("mydir")

If you want to create a directory with a specific path, you can pass the path as an argument to the dir.mkdir method. For example, to create a directory called “mydir” in the “/path/to/dir” directory, you can use the following code:

require 'fileutils'

Dir.mkdir("/path/to/dir/mydir")

If the directory already exists, the dir.mkdir method will raise a Errno::EEXIST error. To avoid this, you can use the dir.exist? method to check if the directory already exists before trying to create it. For example:

require 'fileutils'

if !Dir.exist?("mydir")
  Dir.mkdir("mydir")
end

You can also use the dir.mkdir method to create multiple directories at once by passing multiple arguments to the method. For example, to create directories called “dir1”, “dir2”, and “dir3” in the current working directory, you can use the following code:

require 'fileutils'

Dir.mkdir("dir1", "dir2", "dir3")