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 do |name|
File.file?(File.join(folder, name))
end
puts files
Why this works
Dir.children(folder)gets the names inside the folderFile.join(folder, name)creates the full path safelyFile.file?(...)keeps only real files, not subdirectories
4. Get files matching a pattern
txt_files = Dir.glob("my_folder/*.txt")
puts txt_files
This returns matching paths, for example:
["my_folder/a.txt", "my_folder/b.txt"]
If you only want the base file names:
txt_file_names = Dir.glob("my_folder/*.txt").map do |path|
File.basename(path)
end
puts txt_file_names
5. Read files recursively
files = Dir.glob("my_folder/**/*").select do |path|
File.file?(path)
end
puts files
This looks through subfolders too.
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.
-
First entry:
"report.pdf"File.join(folder, name)becomes:"docs/report.pdf"File.file?("docs/report.pdf")returnstrue- Ruby keeps it.
-
Second entry:
"notes.txt"- Full path becomes
"docs/notes.txt" File.file?returnstrue- Ruby keeps it.
- Full path becomes
-
Third entry:
"images"- Full path becomes
"docs/images" - If
imagesis a folder,File.file?returnsfalse - Ruby removes it.
- Full path becomes
-
Final result:
["report.pdf", "notes.txt"]
puts files- Ruby prints each file name.
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")
Building a file index
A search tool may scan a folder and store file names in a database.
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
unless Dir.exist?(folder)
puts "Folder does not exist"
return
end
Real applications often validate the path before reading it.
Convert paths to file names when needed
Some methods return full paths, but UI code may only need the visible file name.
names = Dir.glob("uploads/*").map { |path| File.basename(path) }
Recursive scans for nested structures
Projects that work with assets, templates, or logs often scan subfolders too.
all_files = Dir.glob("assets/**/*").select { |path| File.file?(path) }
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
Better:
folder = "my_folder"
Dir.children(folder).each do |name|
path = File.join(folder, name)
next unless File.file?(path)
puts File.read(path)
end
3. Building paths manually
Less safe:
path = folder + "/" + name
Better:
path = File.join(folder, name)
4. Assuming Dir.glob returns only file names
files = Dir.glob("my_folder/*.txt")
This returns paths like:
["my_folder/a.txt"]
If you only want the name:
names = Dir.glob("my_folder/*.txt").map { |path| File.basename(path) }
5. Not handling a missing folder
Broken code:
files = Dir.children("missing_folder")
This can raise an error.
Safer version:
folder = "missing_folder"
if Dir.exist?(folder)
files = Dir.children(folder)
else
puts "Folder not found"
end
6. Confusing hidden files with normal files
Some systems have hidden files like .env or .gitignore. Depending on your method and pattern, these may or may not appear, so always test your specific case.
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 Dir.entries
- Use
Dir.childrenwhen you want cleaner results. - Use
Dir.entrieswhen you explicitly need every entry, including special ones.
Dir.children vs Dir.glob
- Use
Dir.childrenwhen you want all names in one folder. - Use
Dir.globwhen you want pattern matching like*.rbor recursive searching.
Names vs full paths
| Need | Better choice |
|---|---|
| Just file names | Dir.children(path) |
| Full matching paths | Dir.glob(pattern) |
| Only regular files | Dir.children(path) + File.file? |
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..Dir.childrendoes not include.and..Dir.globis best for pattern matchingFile.file?(path)checks whether something is a regular file- Use
File.joininstead of manually adding/ - Use
File.basenamewhen you want just the name from a path
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:
Dir.glob("folder/*.txt").map { |path| File.basename(path) }
Can Ruby list files recursively in subfolders?
Yes. Use Dir.glob with **:
Dir.glob("folder/**/*").select { |path| File.file?(path) }
What happens if the folder does not exist?
Ruby may raise an error when you try to read it. Check first with Dir.exist?(folder).
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
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
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.