10

Ruby 中的 require 命令究竟是如何工作的?我使用同一目录中的以下两个文件对其进行了测试。

测试.rb

require 'requirements'
square(2)

需求.rb

def square(x)
    x*x
end

但是当我在与文件“test.rb”和“requirements.rb”相同的目录中运行 ruby​​ test.rb 时,我收到错误消息:

/usr/local/rvm/rubies/ruby-1.9.3-p286/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- requirements (LoadError)
from /usr/local/rvm/rubies/ruby-1.9.3-p286/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from test.rb:1:in `<main>'

我认为这意味着它找不到 requirements.rb 文件。但它与 test.rb 位于同一目录中!如何解决这个问题?

非常感谢提前。对于这样的菜鸟问题,我深表歉意。

4

2 回答 2

34

IIRC, ruby 1.9 doesn't include current dir ('.') to LOAD_PATH. You can do one of these:

# specify relative path
require './test1'

# use relative method
require_relative 'test1'

# add current dir to LOAD_PATH 
$LOAD_PATH.unshift '.'
require 'test1'
于 2013-01-10T09:29:49.467 回答
3

I too just started to learn how ruby works, so I'm not perfectly sure if this helps. But try require_relative instead of require and I think it will work.
Afaik require searches in the ruby libary.

于 2013-01-10T09:30:38.277 回答