Question
In Ruby, what is the best way to require all files from a directory?
For example, if a project has several Ruby files inside a folder, how can you load them efficiently and safely without writing a separate require statement for each file?
Short Answer
By the end of this page, you will understand how Ruby loads files, how to require multiple files from a directory using Dir and glob patterns, when to use require versus require_relative, why file load order matters, and how to avoid common mistakes when auto-loading files in a project.
Concept
Ruby does not have a built-in single command like “require this whole directory.” Instead, developers usually combine:
Dir[]orDir.globto find matching filesrequireorrequire_relativeto load each file
A common pattern looks like this:
Dir[File.join(__dir__, 'my_folder', '*.rb')].sort.each { |file| require file }
This works because:
Dir[...]returns a list of file paths matching a pattern*.rbmeans “all Ruby files in this directory”eachloops through those filesrequireloads each file once
Why this matters
In real Ruby projects, code is often split across multiple files:
- classes
- modules
- service objects
- configuration files
- initializers
Manually writing many require lines becomes repetitive and hard to maintain. Requiring files dynamically can keep setup code shorter and easier to update.
Important detail: load order
The biggest issue is not how to load all files, but in what order they are loaded.
Mental Model
Think of a directory like a shelf full of books.
Dir[...]is you looking across the shelf and collecting all books that match a label, such as all files ending in.rbrequireis opening each book and adding its contents to your program.sortis arranging the books in a predictable order before reading them
If you read Book B before Book A, and Book B refers to something explained only in Book A, you get confused. Ruby gets confused the same way when dependencies are loaded in the wrong order.
Syntax and Examples
Basic syntax
Dir[File.join(__dir__, 'lib', '*.rb')].sort.each do |file|
require file
end
What each part does
__dir__gives the directory of the current fileFile.join(...)builds a safe path*.rbmatches all Ruby files.sortensures a consistent load orderrequire fileloads each file once
Example: load all files in a folder
Suppose your project looks like this:
project/
main.rb
helpers/
math_helper.rb
string_helper.rb
In main.rb:
Dir[File.join(__dir__, 'helpers', '*.rb')].sort.each do |file|
require file
Step by Step Execution
Consider this code:
Dir[File.join(__dir__, 'models', '*.rb')].sort.each do |file|
require file
end
Assume the models folder contains:
models/
user.rb
order.rb
Step by step
1. __dir__
Ruby gets the directory of the current file.
If the current file is:
/app/main.rb
then __dir__ is:
/app
2. File.join(__dir__, 'models', '*.rb')
Ruby builds this pattern:
/app/models/*.rb
3. Dir[...]
Ruby finds matching files:
Real World Use Cases
Plugin systems
A Ruby application may load all plugin files from a plugins/ directory at startup.
Service objects
A project may store many service classes in services/ and require them during boot.
CLI tools
Command-line apps often load command classes from a folder so new commands can be added easily.
Initializers
Some apps load configuration or setup files from an initializers/ directory.
Small libraries and scripts
In a personal project or utility script, auto-requiring all helper files can reduce setup boilerplate.
Real Codebase Usage
In real projects, developers usually use this pattern carefully.
Common patterns
Explicit boot file
A project may have one file like environment.rb or boot.rb that requires all needed files.
Dir[File.join(__dir__, 'services', '*.rb')].sort.each { |file| require file }
Guarding load order with naming
Some teams prefix files with numbers or clear names when order matters:
01_config.rb
02_database.rb
03_models.rb
This is simple, but can become fragile.
Prefer explicit requires for dependencies
If one class clearly depends on another, many developers prefer:
require_relative 'user'
require_relative 'order'
This makes dependencies obvious.
Recursive loading for library folders
Libraries sometimes load all files under lib/:
Dir[.join(__dir__, , , )].sort.each { || file }
Common Mistakes
1. Forgetting to sort files
Without sorting, file order may be inconsistent or unclear.
Broken example:
Dir[File.join(__dir__, 'lib', '*.rb')].each do |file|
require file
end
Better:
Dir[File.join(__dir__, 'lib', '*.rb')].sort.each do |file|
require file
end
2. Using relative strings with require
This may fail if the working directory is different from what you expect.
Broken example:
require 'helpers/math_helper'
If that path is not on Ruby's load path, it will fail.
Better:
require_relative 'helpers/math_helper'
or:
Comparisons
| Approach | Best for | Pros | Cons |
|---|---|---|---|
require_relative 'file' | Loading one known nearby file | Clear and explicit | Repetitive for many files |
require full_path with Dir[] | Loading many files from a directory | Convenient and scalable | Load order can be tricky |
load 'file.rb' | Re-running a file during development or special cases | Reloads every time | Usually not wanted in normal app boot |
| Framework autoloading | Large apps like Rails | Less manual setup | Depends on framework rules |
require vs require_relative
Cheat Sheet
# Load all Ruby files in one directory
Dir[File.join(__dir__, 'folder', '*.rb')].sort.each do |file|
require file
end
# Load all Ruby files recursively
Dir[File.join(__dir__, 'folder', '**', '*.rb')].sort.each do |file|
require file
end
# Load one nearby file
require_relative 'folder/my_file'
Quick rules
- Use
requireto load a file once - Use
require_relativefor a specific local file - Use
Dir[]orDir.globto find matching files - Use
.sortfor predictable order - Use
*.rbto match Ruby files only - Use
**/*.rbfor nested folders - Prefer explicit requires when dependency order matters
Common pattern
FAQ
What is the best way to require all files from a directory in Ruby?
Usually, use Dir[File.join(__dir__, 'folder', '*.rb')].sort.each { |file| require file }. This is a common and simple pattern.
Should I use require or require_relative in Ruby?
Use require_relative for one known local file. Use require when you already have a full path or when loading gems and standard libraries.
Why do people sort files before requiring them?
Sorting creates a predictable load order. Without it, dependencies may break unexpectedly.
Can I require files from subdirectories too?
Yes. Use a recursive glob such as **/*.rb.
Does require load the same file more than once?
Normally, no. Ruby tracks required files and skips reloading them.
Is auto-requiring every file always a good idea?
No. It can hide dependencies and cause order problems. Explicit requires are often better when files depend on each other.
What is the difference between require and load in Ruby?
require loads once. load reads and executes the file every time it is called.
Mini Project
Description
Build a small Ruby app that loads formatter classes from a directory. This demonstrates how to require every Ruby file from a folder and then use the loaded classes in one script.
Goal
Create a script that automatically loads all formatter files from a directory and uses them to format text.
Requirements
- Create a
formattersdirectory with multiple Ruby files. - Load all
.rbfiles from that directory automatically. - Define a different formatter class in each file.
- Use the loaded classes in a main script.
- Make the file loading order predictable.
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.