Dir.glob / mkdir / pwd / entries
Methods for creating directories, listing contents, and matching file paths by pattern. Used for file system operations.
Syntax
# Returns a list of files and directories matching the pattern.
Dir.glob("pattern")
Dir["pattern"] # Shorthand for glob
# Creates a directory.
Dir.mkdir("directory_name")
FileUtils.mkdir_p("path/including/intermediates") # Creates intermediate directories too
# Returns the current working directory.
Dir.pwd
# Returns a list of entries in the directory.
Dir.entries("directory_name")
# Changes to a directory, runs the block, then returns to the original directory.
Dir.chdir("directory_name") { operations }
Method List
| Method | Description |
|---|---|
| Dir.glob | Returns an array of paths matching a wildcard pattern. |
| Dir.mkdir | Creates a directory. Raises an error if intermediate directories do not exist. |
| FileUtils.mkdir_p | Recursively creates a directory, including any intermediate directories. |
| Dir.pwd | Returns the current working directory path as a string. |
| Dir.entries | Returns an array of all entry names in the directory (including "." and ".."). |
| Dir.exist? | Checks whether the specified directory exists. |
Sample Code
require 'fileutils'
# Prints the current working directory.
puts Dir.pwd
# Finds Ruby files using glob.
ruby_files = Dir.glob("*.rb")
puts ruby_files.inspect
# Searches including subdirectories (** matches any depth).
all_ruby_files = Dir.glob("**/*.rb")
puts "Ruby file count: #{all_ruby_files.count}"
# Creates a directory if it does not already exist.
unless Dir.exist?("output")
Dir.mkdir("output")
puts "Created the output directory."
end
# Creates a directory including intermediate directories.
FileUtils.mkdir_p("data/2024/january")
puts "Created nested directories."
# Gets directory entries, excluding "." and "..".
entries = Dir.entries(".").reject { |e| e.start_with?(".") }
puts "Current directory contents: #{entries.inspect}"
# Searches for multiple file extensions at once.
image_files = Dir.glob("*.{png,jpg,gif}")
puts "Image files: #{image_files.inspect}"
Overview
『Dir.glob』searches for files using wildcard patterns (『*』, 『**』, 『?』). Because 『**』matches subdirectories at any depth, you can use it to search across an entire project.
Two methods are available for creating directories: 『Dir.mkdir』and 『FileUtils.mkdir_p』. 『Dir.mkdir』raises an error if the parent directory does not exist, so always use 『FileUtils.mkdir_p』when creating deeply nested paths. To use 『FileUtils』, you must require it with 『require "fileutils"』.
If you find any errors or copyright issues, please contact us.