Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Ruby Programming
Previous Page Home Next Page

Including Other Files

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|"temp.rb","w") { |f|
     f.puts "module Temp\ndef Temp.var() #{i}; end\nend"
   load "temp.rb"
   puts Temp.var

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire