Because Ruby makes it easy to write good, modular code, you'll often
find yourself producing small files containing some chunk of
self-contained functionality---an interface to
x, an algorithm
to do
y, and so on. Typically, you'll organize these files as
class or module libraries.
Having produced these files, you'll want to incorporate them into your
new programs. Ruby has two statements that do this.
load "filename.rb"
require "filename"
|
The
load
method includes the named Ruby source file every
time the method is executed, whereas
require
loads any given
file only once.
require
has additional functionality: it can load
shared binary libraries. Both routines accept relative and absolute
paths. If given a relative path (or just a plain name), they'll search
every directory in the current load path (
$:
, discussed
on page 140) for the file.
Files loaded using
load
and
require
can, of course, include
other files, which include other files, and so on. What might
not be obvious is that
require
is an executable
statement---it may be inside an
if
statement, or it may include a
string that was just built. The search path can be altered at runtime
as well. Just add the directory you want to the string
$:
.
Since
load
will include the source unconditionally, you can
use it to reload a source file that may have changed since the
program began:
5.times do |i|
File.open("temp.rb","w") { |f|
f.puts "module Temp\ndef Temp.var() #{i}; end\nend"
}
load "temp.rb"
puts Temp.var
end
|
produces: