Why to use $LOAD_PATH in Ruby?

Aayush Sharda
2 min readJul 10, 2017

--

One of the first ruby keywords that we learn is “require”. If you have been using gems or built-in libraries, loading dependencies with require just works fine in most of the cases. The “require” keyword and $LOAD_PATH are used for the same task, to locate gems and find the dependent classes. Then why is there a need to use $LOAD_PATH instead.

When your project is exported to other machines it is important that your project confines to the directory names that are specific to the other machine. $LOAD_PATH is used for the exact same purpose. In ruby an identifier starting with a $ symbol is a global variable. $LOAD_PATH is an array of absolute paths i.e it stores the exact location of all the dependencies in the project. The require keyword searches for the dependencies in the array $LOAD_PATH and tries to load it for the file that has a dependency on certain library.

Now, Ruby gems are just source code hierarchies installed in the directories that end up in $LOAD_PATH. But what about when you are working on a gem or a large project where you’ve got source code nested several folders deep. So, here we have a lib folder at the root and a test folder that checks if the code in the lib directory is working properly. Ideally, any code in the test will be written as if the library is already installed, for that to work we need to add the contents of the lib folder into the load path that can be directly used by the files in test directory( using require).

libx = File.expand_path(“../lib”, __FILE__)
$LOAD_PATH.unshift(libx) unless $LOAD_PATH.include?(libx)

The __FILE__ variable is used to find the exact location of the file in which it is defined. This variable makes the code machine independent as the path of the source root folder lib is evaluated relative to the path of the file(__FILE__). Now, the exact location of the source root folder is stored in the libx variable which is then pushed into the $LOAD_PATH array.

The $LOAD_PATH now has the location of the main source folder(lib) which can now be used by the ‘require’ keyword to easily load the files in the lib folder for all the other files.

--

--