Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the difference between `load`, `require`, and `require_relative`

Tags:

ruby

I do not understand the difference between the three methods of importing library or module. As I currently understand it,

load 'file.rb'

would import the contents of the external file into the current file whereas:

require 'file.rb'

would perform the same functionality but would not import a file that had already been imported.

require_relative 'file.rb'

is similar to require, but it will load a file that is only in the current directory whereas require will use the search path $: in an effort to find the file. I have no doubt my understanding of the three mechanisms is flawed. Could anyone offer some clarification?

like image 802
CaitlinG Avatar asked Dec 22 '15 03:12

CaitlinG


1 Answers

load is used when you want to import a file irrespective of whether it has been already imported. require or require_relative is used when you want to import a file only if it has not been already.

From this, it follows that the former is used when the imported file is the object of analysis (data file), whereas the latter is used to provide some features to be used in the program (part of the program, library, framework).

While require can only handle paths relative to $:, require_relative is an extension that can handle paths relative to current directory as well. require_relative is a superset of require, and require can be dispensed (although require_relative is written using require, so it has to be rewritten if require is to be dispensed).

like image 137
sawa Avatar answered Sep 21 '22 05:09

sawa