Cover by David Flanagan, Yukihiro Matsumoto

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required