What is the difference between require_relative and require in Ruby?
- 113,563
- 27
- 250
- 306
- 16,358
- 25
- 69
- 90
-
9Before 1.9.2 there was no need for require_relative, because current directory of script was in `$:`. See http://stackoverflow.com/questions/2900370/ – Nakilon Sep 09 '10 at 20:43
-
1require_relative requires a file specifically pointed to relative to the file that calls it. require requires a file included in the $LOAD_PATH. – Daniel Viglione Mar 29 '18 at 18:38
8 Answers
Just look at the docs:
require_relativecomplements the builtin methodrequireby allowing you to load a file that is relative to the file containing therequire_relativestatement.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"
- 16,978
- 8
- 56
- 70
- 172,072
- 46
- 300
- 307
-
31Is there a difference between `require './file.rb'` and `require_relative 'file.rb'`? – Ciro Santilli Путлер Капут 六四事 Oct 25 '14 at 17:31
-
75@CiroSantilli Yes. `require_relative` allows you to "load a file that is **relative to the file containing the `require_relative` statement**". With `require`, `./` indicates a path that is relative to your current working directory. – Ajedi32 Nov 14 '14 at 15:58
-
19I think it's more important to note that `require str` will always search through directories in $LOAD_PATH. You should use `require_relative` when the file you need to load exists somewhere relative to the file that calls for the loading. Reserve `require` for "external" dependencies. – rthbound Sep 30 '15 at 06:16
require_relative is a convenient subset of require
require_relative('path')
equals:
require(File.expand_path('path', File.dirname(__FILE__)))
if __FILE__ is defined, or it raises LoadError otherwise.
This implies that:
require_relative 'a'andrequire_relative './a'require relative to the current file (__FILE__).This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.
eval('require_relative("a.rb")')raisesLoadErrorbecause__FILE__is not defined insideeval.This is why you can't use
require_relativein RSpec tests, which getevaled.
The following operations are only possible with require:
require './a.rb'requires relative to the current directoryrequire 'a.rb'uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.This is not possible with
require_relativebecause the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with/or./or../), which is always the case forFile.expand_path.
The following operation is possible with both, but you will want to use require as it is shorter and more efficient:
require '/a.rb'andrequire_relative '/a.rb'both require the absolute path.
Reading the source
When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.
require:
VALUE rb_f_require(VALUE obj, VALUE fname) {
return rb_require_safe(fname, rb_safe_level());
}
require_relative:
VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
VALUE base = rb_current_realfilepath();
if (NIL_P(base)) {
rb_loaderror("cannot infer basepath");
}
base = rb_file_dirname(base);
return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}
This allows us to conclude that
require_relative('path')
is the same as:
require(File.expand_path('path', File.dirname(__FILE__)))
because:
rb_file_absolute_path =~ File.expand_path
rb_file_dirname1 =~ File.dirname
rb_current_realfilepath =~ __FILE__
- 302,449
- 85
- 1,093
- 879
From Ruby API:
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.
You can find the documentation at http://extensions.rubyforge.org/rdoc/classes/Kernel.html
- 155,156
- 41
- 207
- 295
- 1,474
- 1
- 11
- 13
Summary
Use require for installed gems
Use require_relative for local files
require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement
require
Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.
When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.
require_relative
This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use
require_relative '../../../filename'
(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).
Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.
- 1
- 1
- 89,394
- 88
- 305
- 468
The top answers are correct, but deeply technical. For those newer to Ruby:
require_relativewill most likely be used to bring in code from another file that you wrote.
for example, what if you have data in ~/my-project/data.rb and you want to include that in ~/my-project/solution.rb? in solution.rb you would add require_relative 'data'.
it is important to note these files do not need to be in the same directory. require_relative '../../folder1/folder2/data' is also valid.
requirewill most likely be used to bring in code from a library someone else wrote.
for example, what if you want to use one of the helper functions provided in the active_support library? you'll need to install the gem with gem install activesupport and then in the file require 'active_support'.
require 'active_support/all'
"FooBar".underscore
Said differently--
require_relativerequires a file specifically pointed to relative to the file that calls it.requirerequires a file included in the$LOAD_PATH.
- 155,156
- 41
- 207
- 295
- 577
- 6
- 10
-
6How can I up vote this answer and bring it all the way to the top, so every visitor of this question page will get a clear and understandable answer right away without breaking their brains? – TiredOfProgramming Mar 08 '18 at 14:31
-
I just saw the RSpec's code has some comment on require_relative being O(1) constant and require being O(N) linear. So probably the difference is that require_relative is the preferred one than require.
- 644
- 6
- 14
-
1Interesting. I landed here looking for info on a speed comparison. My thinking was that `require_relative` was faster because the loader doesn't have to traverse the load path in search of the file. Essentially, `require_relative` provides a direct link. – Clint Pachl Jan 29 '15 at 23:53
-
Early disscussion about [require_relative speed](https://www.ruby-forum.com/topic/2990962) and the RSpec [changelog](https://github.com/rspec/rspec-core/blob/master/Changelog.md#280rc2--2011-12-19). – Clint Pachl Jan 30 '15 at 00:06
I want to add that when using Windows you can use require './1.rb' if the script is run local or from a mapped network drive but when run from an UNC \\servername\sharename\folder path you need to use require_relative './1.rb'.
I don't mingle in the discussion which to use for other reasons.
- 155,156
- 41
- 207
- 295
- 41,178
- 5
- 60
- 104
-
I wanted to know how do you load the `require_relative` file Could you please throw an idea at this http://stackoverflow.com/questions/43487784/appiumruby-load-error-in-the-gem – Emjey Apr 19 '17 at 07:02
absolute path
require './app/example_file.rb'
shortened name
require_relative 'example_file'
- 9
- 2
-
You are totally wrong about that. https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths – Burak Kaymakci Aug 19 '21 at 08:38
-
This is a pretty poor answer. The first example is not an absolute path, and the poster does not bother to explain his examples at all. – shalvah Aug 31 '21 at 08:29