011. require vs require_relative - cwy007/tips-and-skills GitHub Wiki
require uses the current directory that you are running the program from
require_relative uses the directory of where that program itself resides
For example, if a program is in ~/code and is called 1.rb and you've done a cd to that directory
cd ~/code
and you try and run the ruby program with
ruby 1.rb
then within 1.rb
require './2.rb'
require_relative '3.rb'
both will work.
However if you are in another directory, say
cd ~/tmp
and you try and run the program with
ruby ../code/1.rb
then you will get an error such as
/Users/chanweiyan/.rvm/rubies/ruby-2.4.2/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- ./2.rb (LoadError)
from /Users/chanweiyan/.rvm/rubies/ruby-2.4.2/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:59:in `require'
from ../code/1.rb:1:in `<main>'
when trying to use
require './2.rb'
whereas using
require_relative '3.rb'
still works ok _because the reference (to 3.rb) is relative to which directory the program (1.rb) is located in.
require_relative('path')
is the same as:
require(File.expand_path('path', File.dirname(__FILE__)))
require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement.
When you use require to load a file, you are usually accessing functionality that has been properly installed, and made accessible, in your system. require does not offer a good solution for loading files within the project’s code. This may be useful during a development phase, for accessing test data, or even for accessing files that are "locked" away inside a project, not intended for outside use.
For example, if you have unit test classes in the "test" directory, and data for them under the test "test/data" directory, then you might use a line like this in a test case:
require_relative "data/customer_data_1"
Since neither "test" nor "test/data" are likely to be in Ruby’s library path (and for good reason), a normal require won’t find them. require_relative is a good solution for this particular problem.
You may include or omit the extension (.rb or .so) of the file you are loading.
path must respond to to_str.
reference link: https://stackoverflow.com/questions/3672586/what-is-the-difference-between-require-relative-and-require-in-ruby