We use directory operations to look inside folders, create new folders, or remove them. This helps us organize and manage files on the computer.
Dir operations for directories in 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.
files = Dir.entries(".") puts files
Dir.mkdir("new_folder") puts Dir.exist?("new_folder")
Dir.rmdir("old_folder")Dir.chdir("new_folder") do puts Dir.pwd end
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.
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}"
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.
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.