What is the difference between require, require_relative, and load?
Last updated
All three load Ruby code, but differ in path resolution and whether they re-run a file. require loads once from the load path, require_relative loads once relative to the current file, and load runs the file every time it is called.
require:Searches the load path ($LOAD_PATH) and gems; needs an absolute path or a name it can resolve.
Loads a file only once: tracks it in
$LOADED_FEATURESand returnsfalseon repeat calls.
require_relative:Resolves the path relative to the location of the current source file, not the working directory.
Also loads only once; ideal for requiring files within your own project.
load:Executes the file every time it is called (no once-only tracking); useful for reloading changed code.
Requires the full filename including
.rb, and resolves via the load path.
Rule of thumb: Use
requirefor gems/libraries,require_relativefor project files, andloadonly when you deliberately need re-execution.
- https://docs.ruby-lang.org/en/master/Kernel.html
- https://rubylearning.in/courses/ruby-basics/including-other-files/
- https://practicingruby.com/articles/ways-to-load-code
- https://blog.appsignal.com/2023/04/19/how-to-load-code-in-ruby.html
- https://docs.ruby-lang.org/ja/latest/method/Kernel/m/require.html
- https://medium.com/@ellishim/understanding-require-vs-require-relative-vs-require-all-80e3b26d89e6
- https://www.rubydoc.info/stdlib/core/Kernel%3Arequire_relative
- https://docs.ruby-lang.org/ja/latest/method/Kernel/m/require_relative.html