What are the paths that "require" looks up by default?
Solution 1
It depends on your platform, and how Ruby was compiled, so there is no "the" answer to this. You can find out by running:
ruby -e 'puts $:'
Generally, though, you have the standard, site, and vendor Ruby library paths, including an arch, version, and general directory under each.
Solution 2
Ruby looks in all the paths specified in the $LOAD_PATH
array.
You can also add a directory to search like so:
$LOAD_PATH.unshift File.expand_path('../path/from/this/file/to/another/directory', __FILE__)
Solution 3
additional paths can be specified by setting RUBYLIB environment variable
Solution 4
The $LOAD_PATH global variable (also named $:) contains the list of directories that are searched.
See: http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-require
Solution 5
When calling ruby
on command line, you can provide additional search paths using the -I
argument. Compare the output of
$ ruby -e 'puts $:'
with the output of
$ ruby -I /tmp -e 'puts $:'
note how the second one lists /tmp
as an option. You can use multiple -I
to add multiple path.
You can also use it with the shebang:
#!/usr/bin/ruby -I /tmp -I /usr/local/lib/ruby
Comments
-
Mark Provan almost 2 years
In Ruby, I have been told that when doing
require "some_file"
Ruby will look for the file in certain places.
I know that it looks for
some_file.rb
, but where does it look for it by default? -
Perry over 12 yearsThere is a "the" answer. The $: or $LOAD_PATH variable does indeed give the full list of places that are searched. You yourself noted a simple and clean way to print that out...
-
Daniel Pittman over 12 yearsAh. Depends how you read the question: there is "the" answer to where this Ruby looks, but it will change if you run a different Ruby or on a different platform. eg: MRI 1.8.7 and REE would use different paths, or Darwin and Linux MRI use subtly different paths. I wasn't sure which, so felt more comfortable with this answer.
-
Perry over 12 yearsThat is true enough, though I'm guessing the questioner simply wanted to know how to find out what the load path was rather than assuming it was constant across platforms.
-
Daniel Pittman over 12 yearsYou might well be right about that. It seemed more complex the first time I read it. :)