Ruby - Create a New Directory

1. Introduction

In Ruby, creating directories is a straightforward process with the help of the Dir class. This post will guide you through the steps to create a new directory in Ruby.

A directory, often referred to as a folder, is a file system structure that contains files and other directories. It provides an organized way to store files on a computer.

2. Program Steps

1. Load the required library/module.

2. Define the directory name/path.

3. Use the mkdir method from the Dir class to create the directory.

4. Handle any potential errors using exception handling.

3. Code Program

# Require the fileutils module
require 'fileutils'
# Define the directory name
dir_name = "new_directory"
# Create the new directory
begin
  Dir.mkdir(dir_name)
  puts "Directory '#{dir_name}' created successfully!"
rescue SystemCallError => e
  puts "Directory creation failed: #{e.message}"
end

Output:

Directory 'new_directory' created successfully!
Or
Directory creation failed: [Error message depending on the issue]

Explanation:

1. require 'fileutils': While the fileutils module is not directly used in the above code, it's a useful module for many file and directory operations, so it's good to be familiar with it.

2. dir_name = "new_directory": Here, we define the name of the directory we want to create.

3. The Dir.mkdir(dir_name) method is used to create a new directory with the specified name.

4. We use begin..rescue for exception handling to handle any potential errors, such as if the directory already exists or if there are permission issues.


Comments