0
0
Rubyprogramming~5 mins

Dir operations for directories in Ruby

Choose your learning style9 modes available
Introduction

We use directory operations to look inside folders, create new folders, or remove them. This helps us organize and manage files on the computer.

You want to list all files inside a folder to see what is there.
You need to create a new folder to save some files.
You want to check if a folder exists before saving something.
You want to delete an empty folder you no longer need.
You want to change the current folder your program is working in.
Syntax
Ruby
Dir.entries(path)
Dir.mkdir(path)
Dir.exist?(path)
Dir.rmdir(path)
Dir.chdir(path) do
  # code inside new directory
end

Dir.entries(path) returns an array of all files and folders inside the given path.

Dir.mkdir(path) creates a new directory at the given path.

Examples
This lists all files and folders in the current directory.
Ruby
files = Dir.entries(".")
puts files
This creates a folder named 'new_folder' and checks if it exists.
Ruby
Dir.mkdir("new_folder")
puts Dir.exist?("new_folder")
This removes the folder named 'old_folder' if it is empty.
Ruby
Dir.rmdir("old_folder")
This changes the current directory to 'new_folder' temporarily and prints its path.
Ruby
Dir.chdir("new_folder") do
  puts Dir.pwd
end
Sample Program

This program shows files in the current folder, creates a new folder if it doesn't exist, changes into it to list files, then removes the folder.

Ruby
puts "Current directory files:"
puts Dir.entries(".")

folder_name = "test_dir"

unless Dir.exist?(folder_name)
  Dir.mkdir(folder_name)
  puts "Created directory: #{folder_name}"
else
  puts "Directory already exists: #{folder_name}"
end

puts "Changing to #{folder_name} and listing files:"
Dir.chdir(folder_name) do
  puts Dir.entries(".")
end

Dir.rmdir(folder_name)
puts "Removed directory: #{folder_name}"
OutputSuccess
Important Notes

Dir.entries always includes "." (current folder) and ".." (parent folder) in the list.

You can only remove empty directories with Dir.rmdir. To remove folders with files, you need other methods.

Use Dir.chdir with a block to safely change directories and return back automatically.

Summary

Use Dir.entries to see files and folders inside a directory.

Create folders with Dir.mkdir and check existence with Dir.exist?.

Remove empty folders with Dir.rmdir and change directories with Dir.chdir.