Kernel#load
load(filename[, wrap]) -> true Boolean · Updated March 13, 2026 · Kernel Methods The load method reads and executes Ruby code from a file. Unlike require, which tracks loaded files to prevent double-loading and is designed for libraries, load executes the file every time it’s called and is typically used for loading scripts or configuration files.
Key Differences from require
Understanding when to use load versus require is important in Ruby development. require is designed for loading libraries and tracks dependencies, while load is for executing scripts where you want the code to run fresh each time.
Practical Examples
Basic File Loading
# Load and execute a Ruby script
load "setup.rb"
# With full path
load "/path/to/scripts/initialize.rb"
Loading with Variable Isolation
# The wrap parameter creates an isolated module
load "plugin.rb", true # Code runs in a new module, won't affect main namespace
# Without wrap (default false), code runs in the global namespace
load "config.rb" # Constants and methods become available globally
Dynamic Script Execution
# Load scripts from a directory
Dir.glob("scripts/*.rb").each { |script| load script }
# Conditional loading based on environment
load "development.rb" if ENV["RACK_ENV"] == "development"
Reloading Code During Development
# load executes every time, useful for reloading
loop do
load "hot_reload.rb" # Re-executes the file each iteration
sleep 5
end
Loading Configuration Files
# config.rb could contain:
# DATABASE_HOST = "localhost"
# DATABASE_PORT = 5432
load "config.rb"
puts DATABASE_HOST # => "localhost"
Important Considerations
Path Resolution
# load uses the current directory or absolute paths
load "./lib/helpers.rb"
load "/absolute/path/to/script.rb"
# Or add to load path
$LOAD_PATH.unshift("/my/library/path")
load "library.rb"
Error Handling
begin
load "script.rb"
rescue LoadError => e
puts "Could not load script: #{e.message}"
rescue SyntaxError => e
puts "Syntax error in script: #{e.message}"
end
Security Concerns
Be cautious when loading files from untrusted sources. Unlike eval, load executes the entire file, which could contain any Ruby code including system commands.
# Dangerous - don't load untrusted files!
load user_uploaded_file # Could contain `system("rm -rf /")`
When to Use load
Use load when you need to:
- Execute a script every time (not just once)
- Run scripts without the library loading mechanism
- Load configuration files that should be re-evaluated
- Create plugin systems where code should be reloaded
Use require when loading libraries that should only be loaded once and where dependency management matters.