O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

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

require 'req'    # leave off the .rb extension
speak

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

% ruby reqtest.rb
Hello

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required