How to Import Ruby Classes
"Require," "load" and "include" are all methods that can be used to import classes into an existing program in Ruby. "Load" and "require" both load libraries into a program, but both serve different purposes. "Require" runs a file just once in a program, while "load" runs the file each time the "load" method is called. "Include" is used to extend existing classes using modules, referred to as "mixins." How you import classes into Ruby depends on what you want the program to do.
Instructions
-
-
1
Insert "require" or "load" into the code to import classes. Use the former to run the code once; use the latter to run the code each time "load" is used:
require 'filename'
or
load 'filename.rb'
"Load" requires a file extension, while "require" does not.
-
2
Replace "require" with "require_relative" if the file you're loading into the program is in the same directory as the program you're writing.
-
-
3
Insert "include" in between a class to extend the features of that class. For example:
class Foo
include Enumerable
# . . .
end
-
1
Tips & Warnings
If Ruby doesn't recognize the path to the file, insert the full file path in between the quotes:
require 'c:\users\username\documents\rubyfiles\mycode'
Use "../mycode" if the library is contained in the parent directory.
References
- Ruby: Visual Quickstart Guide; Larry Ullman; 2008