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.
If one file depends on a class or module defined in another file, loading them in the wrong order can raise errors such as:
uninitialized constant MyClass
That is why many examples use .sort before requiring files. Sorting gives a predictable order.
require vs require_relative
requireloads a file using Ruby's load path or an absolute pathrequire_relativeloads a file relative to the current file
When you already have a full path from Dir[...], plain require usually works well.
If you are loading a single nearby file, require_relative is often clearer.
When not to auto-require everything
Auto-loading every file in a directory can be convenient, but it is not always the best design.
Avoid it when:
- file order is important and fragile
- only a few files are actually needed
- loading everything increases startup time unnecessarily
- explicit requires would make dependencies clearer
In small scripts it can be useful. In larger apps, frameworks or explicit loading strategies are often better.
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
end
Now both helper files are loaded.
Example: recursive loading
If you want to load Ruby files from nested folders too:
Dir[File.join(__dir__, 'lib', '**', '*.rb')].sort.each do |file|
require file
end
Here:
**means “search subdirectories too”
Example: requiring one nearby file
For a single file, this is often simpler:
require_relative 'helpers/math_helper'
Use this when you know exactly which file you need.
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:
['/app/models/order.rb', '/app/models/user.rb']
4. .sort
Ruby sorts the file names alphabetically.
For example:
['/app/models/order.rb', '/app/models/user.rb']
This gives a predictable order each time.
5. .each do |file|
Ruby loops through the array one file at a time.
First iteration:
file = '/app/models/order.rb'
Second iteration:
file = '/app/models/user.rb'
6. require file
Ruby loads each file once.
If the same file is required again later, Ruby usually skips reloading it.
Why this matters
If order.rb depends on user.rb, alphabetical sorting may or may not be correct. If dependency order matters, you may need explicit requires instead of bulk loading.
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[File.join(__dir__, 'lib', '**', '*.rb')].sort.each { |file| require file }
Framework-managed loading
In Rails and some modern setups, developers often rely on framework autoloading instead of manually requiring every file.
Practical advice
- Use bulk loading for convenience in controlled folders
- Use explicit requires when order or clarity matters
- Keep folder structure predictable
- Avoid mixing unrelated files in auto-loaded directories
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:
require File.join(__dir__, 'helpers', 'math_helper.rb')
3. Loading files in the wrong dependency order
Broken example:
# order.rb uses User, but user.rb is loaded later
Dir[File.join(__dir__, 'models', '*.rb')].sort.each do |file|
require file
end
If alphabetical order is wrong, this can break.
Avoid this by:
- requiring dependent files explicitly
- designing files to reduce circular dependencies
4. Using load when you mean require
load re-reads the file every time.
load 'my_file.rb'
This is usually not what you want for normal application setup.
Prefer:
require 'my_file'
5. Requiring non-Ruby files by mistake
Be specific with your glob pattern.
Better:
Dir[File.join(__dir__, 'lib', '*.rb')]
instead of something too broad.
6. Auto-loading everything without a reason
Sometimes the simplest and clearest code is just a few explicit require_relative lines.
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
| Method | How it finds files | Typical use |
|---|---|---|
require | Load path or full path | Gems, standard libraries, full paths from Dir[] |
require_relative | Relative to current file | Local project files nearby |
Bulk require vs explicit require
| Style | Advantage | Tradeoff |
|---|---|---|
| Bulk require | Less repetitive | Hidden dependencies |
| Explicit require | Clear dependency graph | More manual code |
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
Dir[File.join(__dir__, 'lib', '*.rb')].sort.each { |f| require f }
Edge cases
- File order may break dependencies
requiredoes not reload an already-loaded fileloaddoes reload files- Paths based on current working directory can be unreliable
__dir__helps build stable paths
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
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.