ruby - 为什么即使 "file.rb"不在加载路径中,加载 "."仍然可以工作?

标签 ruby load-path

我在/Projects/test 中创建了一个项目,其中包含以下文件:

/Projects/test/first.rb
/Projects/test/second.rb

first.rb中,我这样做:

load 'second.rb'

并且它被正确加载。但是,如果我打开控制台并输入 $:,我在加载路径中看不到当前目录 "."。 Ruby 如何知道从哪里加载 'second.rb'

最佳答案

请参阅 Kernel#load 的文档显然:

Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program’s global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

如果加载'second.rb' - second.rb已在内部解析为绝对路径/Projects/test/second.rb,因为您所需的目录中的文件与所需的文件目录相同。尚未针对您的情况在 $: 中列出的目录中搜索任何内容。

永远记住另一种方式 - 加载方法首先在当前目录中查找文件

关于ruby - 为什么即使 "file.rb"不在加载路径中,加载 "."仍然可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19946411/

相关文章:

ruby-on-rails - 不理解 Arel 的用法(Rails)

python - 清理从 csv 文件中提取的字符串

ruby-on-rails - 运行抽佣 Assets :precompile fails when there's no tables (yet)

ruby - 如何将 gem 配置为只使用系统 gem?

ruby - 在Ruby编程语言中,$:叫什么名字

ruby - 重复一个序列并将其与数组交错

ruby - rails 中 link_to 描述中的条件

ruby - 为什么 Ruby 1.9.2 从 LOAD_PATH 中删除 ".",还有什么替代方案?

ruby-on-rails - "$"字符在 Ruby 中是什么意思?