Runtime Extension of Ruby's World: require

By far the most important tool for getting a program in one file to see what's in other program files is the require method.

At its simplest, require causes a running program to pull in, and evaluate, the code from a file on disk. You can try this out easily. You need to create two files. Call the first req.rb, and put these lines in it:

def speak
  puts "Hello."

The second file should be called reqtest.rb, and its contents should be this:

require 'req'    # leave off the .rb extension

Now test reqtest.rb. It's the top-level script, but when the interpreter runs it, both files are consulted.

% ruby reqtest.rb

As you can see, the require line in reqtest.rb caused the code in req.rb to ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.