Loading and Requiring Modules

Ruby programs may be broken up into multiple files, and the most natural way to partition a program is to place each nontrivial class or module into a separate file. These separate files can then be reassembled into a single program (and, if well-designed, can be reused by other programs) using require or load. These are global functions defined in Kernel, but are used like language keywords. The same require method is also used for loading files from the standard library.

load and require serve similar purposes, though require is much more commonly used than load. Both functions can load and execute a specified file of Ruby source code. If the file to load is specified with an absolute path, or is relative to ~ (the user’s home directory), then that specific file is loaded. Usually, however, the file is specified as a relative path, and load and require search for it relative to the directories of Ruby’s load path (details on the load path appear below).

Ruby 1.9 also defines a require_relative method. It works like require, except that it ignores the load path and searches for the named file relative to the directory from which the invoking code was loaded.

Despite their overall similarities, there are important differences between load and require:

  • In addition to loading source code, require can also load binary extensions to Ruby. Binary extensions are, of course, implementation-dependent, but in C-based implementations, they typically take the form ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.