Ruby - LoadError on require
14,799
The better way to use
require_relative "sort"
intead of
require "sort"
Thanks, @Jörg W Mittag.
Or you can add a path where ruby should search your files (can be a security risk):
$:.unshift File.join(File.dirname(__FILE__), ".") # current directory
require 'sort'
Comments
-
Aly almost 2 years
I have the following two files:
main.rb
andsort.rb
located in the same folder. Inmain.rb
I have the following code:require 'sort' Sort.insertion_sort([1,2,3,4]).each {|x| print "#{x}, "}
When I try and run this via ruby
main.rb
I get the following error:<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- sort (LoadError) from <internal:lib/rubygems/custom_require>:29:in `require' from main.rb:1:in `<main>'
Any ideas why? Thanks
-
Adrien Jarthon about 13 yearsIf he's running using ruby main.rb, it should no be the problem here
-
Adrien Jarthon about 13 yearsyes it should work, specifying the extension just help sometimes getting a better error description. especially for permissions or file-system problems
-
Vasiliy Ermolovich about 13 yearsif he's running from the directory with main.rb file, otherwise it will be the problem here
-
Aly about 13 yearsmain is in the same directory as sort.rb
-
Aly about 13 yearsI am running from the directory with main.rb in it
-
Jörg W Mittag about 13 yearsPlease do not ever do this. There is a reason why
.
was removed from the$LOAD_PATH
. If you want to require a file relative to the location of the currently executing file, userequire_relative
, that's what it's there for. -
oligan about 13 years@Joerg: Is something like
$:.unshift File.join(File.dirname(__FILE__), "lib")
also a risk? -
Jörg W Mittag about 13 years@Andrew Grimm: No. Any attacker who would be able to inject files into that directory would probably be able to just edit the script anyway. The problem with adding
.
to the$LOAD_PATH
is when I can get you to run your script from inside a directory that I own, I can inject pretty much arbitrary code into your script by e.g. putting a file namedsort.rb
in my directory, which will be found before yours. Especially if you useArray#unshift
to put.
at the beginning of$LOAD_PATH
. -
Jörg W Mittag about 13 years@Andrew Grimm: Note, however, that this sort of relative
$LOAD_PATH
manipulation is still a smell, since your package manager should do that for you. E.g. RubyGems automatically adds your Gem'slib
directory, or any other directory/ies you specify to the$LOAD_PATH
anyway, as does Bundler, and if you use some other package management system, then it's the packager's and/or the system administrator's job to do that. You shouldn't need to do that yourself.