Question
I want to retrieve the names of all files in a folder using Ruby.
Short Answer
By the end of this page, you will understand how Ruby reads directory contents, how to list file names from a folder, how to filter out directories, and which Ruby methods are commonly used for this task in real programs.
Concept
In Ruby, working with files and folders is usually done with the built-in Dir and File classes.
If you want all file names from a folder, the main idea is:
- read the directory entries
- decide whether you want everything or only files
- optionally build full paths
- optionally filter out special entries like
.and..
A folder can contain:
- regular files
- subdirectories
- hidden files
- special entries such as
.and..
That means "get all file names" can mean different things depending on your goal:
- list every entry in the directory
- list only regular files
- list files matching a pattern such as
*.txt - list files recursively from nested folders
This matters in real programming because many applications need to inspect folders:
- import data files
- process uploaded documents
- scan log directories
- load configuration files
- generate reports from many files
Ruby gives you a few clean ways to do this. The most common are:
Dir.entries(path)Dir.children(path)Dir.glob(pattern)- filtering with
File.file?(path)
For beginners, Dir.children is often the easiest starting point because it returns the names inside a folder without including . and ...
Mental Model
Think of a folder like a drawer in a cabinet.
Dir.entriesopens the drawer and tells you everything inside, including the special labels.and..Dir.childrenopens the drawer and shows only the actual visible itemsFile.file?helps you check whether an item is a document instead of another drawerDir.globis like saying, "Show me only items whose labels match this pattern"
So the process is:
- open the drawer
- look at each item
- keep only the ones you need
Syntax and Examples
The most common ways to list file names in Ruby are shown below.
1. List all entries in a folder
files = Dir.entries("my_folder")
puts files
This returns entries such as:
[".", "..", "file1.txt", "file2.txt"]
Dir.entries includes . and .., so you often need to remove them.
2. List children without . and ..
files = Dir.children("my_folder")
puts files
This usually returns cleaner results:
["file1.txt", "file2.txt", "images"]
3. Get only regular files
folder = "my_folder"
files = Dir.children(folder).select ||
.file?(.join(folder, name))
puts files
Step by Step Execution
Consider this example:
folder = "docs"
files = Dir.children(folder).select do |name|
File.file?(File.join(folder, name))
end
puts files
Assume the docs folder contains:
report.pdf
notes.txt
images
Step by step:
-
folder = "docs"- A variable stores the folder name.
-
Dir.children(folder)- Ruby reads the contents of
docs. - It returns something like:
["report.pdf", "notes.txt", "images"]
- Ruby reads the contents of
-
.select do |name| ... end- Ruby checks each entry one by one.
selectkeeps only the entries where the block returnstrue.
Real World Use Cases
Here are common situations where this is useful:
Processing uploaded files
A script may scan an uploads folder and process each image or document.
Dir.children("uploads").each do |name|
path = File.join("uploads", name)
next unless File.file?(path)
puts "Processing #{name}"
end
Importing CSV files
A data import job may look for all .csv files in a directory.
csv_files = Dir.glob("imports/*.csv")
Reading log files
A maintenance script may gather all log file names before compressing them.
log_files = Dir.glob("logs/*.log")
Loading configuration files
An app may load all Ruby config files from a config folder.
config_files = Dir.glob("config/*.rb")
Real Codebase Usage
In real projects, developers usually do more than just list names.
Common patterns
Filter early
Only keep valid files before doing more work.
Dir.children(folder).each do |name|
path = File.join(folder, name)
next unless File.file?(path)
# process file
end
This is a guard clause pattern using next.
Use File.join instead of manual string building
path = File.join(folder, name)
This is safer than:
path = folder + "/" + name
Use glob patterns for file types
json_files = Dir.glob(File.join(folder, "*.json"))
This makes code easier to read when you only want certain file extensions.
Handle missing directories
Common Mistakes
Beginners often run into a few predictable issues.
1. Forgetting that Dir.entries includes . and ..
Broken expectation:
files = Dir.entries("my_folder")
puts files
You may see:
[".", "..", "file1.txt"]
Use Dir.children if you do not want those special entries.
files = Dir.children("my_folder")
2. Treating directories as files
Broken code:
Dir.children("my_folder").each do |name|
puts File.read(name)
end
Problem:
nameis not the full path- some entries may be directories
Comparisons
Here is how the main options differ.
| Method | Returns | Includes . and .. | Best for |
|---|---|---|---|
Dir.entries(path) | All entries | Yes | Low-level directory listing |
Dir.children(path) | Child names | No | Clean listing of names |
Dir.glob("path/*") | Matching paths | No | Pattern matching |
Dir.glob("path/**/*.txt") | Recursive matches | No | Recursive searches |
Dir.children vs
Cheat Sheet
# All entries, including "." and ".."
Dir.entries("folder")
# Names inside folder, excluding "." and ".."
Dir.children("folder")
# Only regular files in a folder
Dir.children("folder").select do |name|
File.file?(File.join("folder", name))
end
# Files matching a pattern
Dir.glob("folder/*.txt")
# Recursive file search
Dir.glob("folder/**/*").select { |path| File.file?(path) }
# Get file name from full path
File.basename("folder/test.txt")
# Safely build paths
File.join("folder", "test.txt")
# Check whether a directory exists
Dir.exist?("folder")
Quick rules
Dir.entriesincludes.and..- does not include and
FAQ
How do I get all file names from a folder in Ruby?
Use Dir.children(folder) to get names inside a folder. If you want only regular files, filter with File.file?.
What is the difference between Dir.entries and Dir.children in Ruby?
Dir.entries includes the special entries . and .., while Dir.children excludes them.
How do I get only files and not subdirectories in Ruby?
Use:
Dir.children(folder).select { |name| File.file?(File.join(folder, name)) }
How do I list only .txt files in a Ruby folder?
Use a glob pattern:
Dir.glob("folder/*.txt")
How do I get file names without the folder path in Ruby?
Use File.basename:
Mini Project
Description
Build a small Ruby script that scans a folder and prints only the names of regular files. This demonstrates directory reading, path building, and filtering out subdirectories.
Goal
Create a script that lists only file names from a chosen folder and ignores directories.
Requirements
- Store the folder path in a variable.
- Check that the folder exists before reading it.
- Read the folder contents.
- Filter out anything that is not a regular file.
- Print each file name on its own line.
Keep learning
Related questions
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Convert a Unix Timestamp to Ruby DateTime
Learn how to convert Unix timestamps to Ruby DateTime and Time objects, with examples, differences, pitfalls, and practical Ruby usage.