How to require a ruby file from another directory

require will search for files in only a set of locations referred to as the “Load Path.” You can view the load path by using the global variable $LOAD_PATH in a script or irb session. If it is not in the load path, it won’t find it.

Ruby 1.9 introduced require_relative which searches using the current file’s location as a starting point.

# Will search $LOAD_PATH for file. 
require 'test/unit'
# Notice the "https://stackoverflow.com/" which tells it to look in the 
# 'test' folder for a file named 'unit.rb'

# Will look in current folder of file
require_relative 'my_folder/my_file'
# Will search in 'my_folder' for the file 'my_file.rb'

Note that require_relative will not work in irb.

Also note, that if you really want to use require, you can start your script by adding a location to the $LOAD_PATH variable.

$LOAD_PATH << File.join('users', 'yourusername', 'your_folder')
# or
$LOAD_PATH << File.dirname(__FILE__)
# The second one enables you to move the file around on your
# system and still operate correctly
require 'my_file'

Here’s some additional documentation from Ruby-Doc:

  • $LOAD_PATH
  • require
  • require_relative
  • File.dirname
  • __FILE__

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)