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

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

load 'file.rb' 

imports the contents of an external file into the current file, whereas:

 require 'file.rb' 

will perform the same functions, but will not import an already imported file.

 require_relative 'file.rb' 

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 attempt to find the file. I have no doubt that my understanding of these three mechanisms is erroneous. Can anyone provide clarification?

+5
source share
1 answer

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

It follows that the former is used when the imported file is the object of analysis (data file), while the latter is used to provide some functions that will be used in the program (part of the program, library, framework).

Although require can only handle paths relative to $: require_relative is an extension that can also handle paths relative to the current directory. require_relative is a superset of require , and require can be issued (although require_relative written using require , so you need to rewrite it if you need to send require ).

+8
source

Source: https://habr.com/ru/post/1238912/


All Articles