当我尝试运行你的代码,我得到了以下错误消息
$ ruby c.rb
~/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- a (LoadError)
from /Users/Sonna/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from c.rb:2:in `<main>'
这只不过是说,它采用了Kernel's require method 无法找到a.rb
文件,然后引发和LoadError
例外。
为了所需要的文件,你可以使用Kernal's require_relative
method
require_relative "a"
require_relative "b"
,它会那些a
& b
文件相对c
文件。
或者你可以将下面的代码行添加到您的c.rb
文件,它是用Ruby宝石用来加载自己的自定义脚本 常见的约定/库
current_directory = File.expand_path("../", __FILE__)
$LOAD_PATH.unshift(current_directory) unless $LOAD_PATH.include?(current_directory)
这将增加当前目录../
从当前文件__FILE__
, 将其扩展为所述当前目录的aboslute路径,并将其添加到现有Load Path全局变量的 ;例如
puts $LOAD_PATH
# => ["~/Projects/ruby/stackoverflow_questions/the_scope_of_require",
# "/usr/local/Cellar/rbenv/1.0.0/rbenv.d/exec/gem-rehash",
# "~/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/did_you_mean-1.0.0/lib",
# "~/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0",
# "~/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/x86_64-darwin15",
# "~/.rbenv/versions/2.3.1/lib/ruby/site_ruby",
# "~/.rbenv/versions/2.3.1/lib/ruby/vendor_ruby/2.3.0",
# "~/.rbenv/versions/2.3.1/lib/ruby/vendor_ruby/2.3.0/x86_64-darwin15",
# "~/.rbenv/versions/2.3.1/lib/ruby/vendor_ruby",
# "~/.rbenv/versions/2.3.1/lib/ruby/2.3.0",
# "~/.rbenv/versions/2.3.1/lib/ruby/2.3.0/x86_64-darwin15"]
其中require
内部使用的文件名,找到,如果它没有给出 绝对路径
If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $LOAD_PATH ($:)
.
-- Kernel's require method
所以,当我再次运行你的代码,我看到下面的
$ ruby c.rb
hello world
应该注意的是,
A file will not be loaded again if its path already appears in $"
. For example, require 'a'; require './a'
will not load a.rb
again.
-- Module: Kernel (Ruby 2_4_0)
所以只要你的require
方法之一出现在 这个文件被调用的方法之一之前,它就应该工作;所以您的两个例子就可以了(如 只要任一目录下的仰卧被添加到$LOAD_PATH
或使用 require_relative
代替)
有代码的答案中的一个注意到的错误。我没有为需求添加'。/'。 –