What are the paths that “require” looks up by default?

喜欢而已 提交于 2019-11-27 00:16:23

问题


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?


回答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.




回答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__)



回答3:


additional paths can be specified by setting RUBYLIB environment variable




回答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




回答5:


require(string) => true or false

Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ".rb", it is loaded as a source file; if the extension is ".so", ".o", or ".dll", or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on to the name. The name of the loaded feature is added to the array in $:.




回答6:


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


来源:https://stackoverflow.com/questions/9474299/what-are-the-paths-that-require-looks-up-by-default

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!