Differences between load, autoload, require, and require_relative in Ruby
In Ruby, there are several ways to load external libraries and Ruby programs. The load
, autoload
, require
, and require_relative
methods all serve different purposes, and it would be great to understand the differences.
Load method
This will load the Ruby file with the given filename and execute its code. The file can be either an absolute path or a relative path using .
or ..
. Each call to load will load and execute the file, even if it has already been loaded. This method is useful for making changes to a file while a program is running and examining them immediately without reloading the application.
load 'myscript.rb'
Autoload method
This method takes a module name and a filename as arguments. It registers the filename to load the first time the specified module is accessed. This speeds up library initialization by lazily loading modules that your code depends on.
autoload(:MyModule, "domains/user/my_module.rb")
Require method
Similar to load. However, it won't load the file if it's already loaded. The constants, classes, modules, and global variables in the required file will be available to the calling program. If the filename doesn't start with ./
or ../
or is an absolute path, the file is searched for in the directories listed in $LOAD_PATH
.
require 'my_module.rb'
Require_relative method
This method works similarly to require
but it loads the specified file relative to the current directory instead of looking for it in $LOAD_PATH
.
require_relative 'my_module.rb'
Summary
- Use
load
to get any changes you made to a file while the program was running since the code from the file will always be called, especially during development. - Use
autoload
to quickly load the modules, which will speed up the initialization of your library. - Use
require
if you want to use external gems (which will use the$LOAD_PATH
to try to find the files). - Use
require_relative
for local files that are relative to the active working directory (the path between the files will be the same).