Ruby - Including Modules from Files

Introduction

To use code from another file is to load that file using the require method, like this:

require( "./testmod.rb" )

Optionally, you may omit the file extension:

require( "./testmod" )  # this works too

If no path is given, the required file must be in the current directory, on the search path, or in a folder listed in the predefined array variable $:.

You can add a directory to this array variable using the usual array-append method, <<, in this way:

$: << "C:/mydir"

The global variable, $: contains an array of strings representing the directories that Ruby searches when looking for a loaded or required file.

Demo

puts( $: )

Result

A single dot . represents the current directory.

You could use the require_relative method

require_relative( "testmod.rb" )    # Ruby 1.9 only

If $: doesn't contain the current directory, you could add it.

$: << "."              # add current directory to array of search paths
require( "testmod.rb" )

The require method returns a true value if the specified file is successfully loaded; otherwise, it returns false.

If the file does not exist, it returns a LoadError.

You can simply display the result.

 Pre:puts(require( "testmod.rb" )) #=> true, false or LoadError

If the file, testmod.rb, contains this code:

def sing
     puts( "hi")
end

puts( "module loaded")
sing

when the require_module.rb program is run and it requires testmod.rb, this will be displayed:

module loaded
hi

When a module is declared in the required file, it can be mixed in:

require( "testmod.rb")
include MyModule       #mix in MyModule declared in testmod.rb

Related Topic