用红宝石实例化Foo?
问题描述:
我如何instantiate Foo从bar.rb
?用红宝石实例化Foo?
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$ cat foo.rb
#file: foo.rb
class Foo
def initialize
puts "foo"
end
end
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$ cat bar.rb
#file: bar.rb
require 'foo'
Foo.new
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$ ruby bar.rb
/home/thufir/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- foo (LoadError)
from /home/thufir/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from bar.rb:2:in `<main>'
[email protected]:~/ruby/hello$
此刻不使用模块。正常工作时Foo
是在线:
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$ ruby bar.rb
foo
[email protected]:~/ruby/hello$
[email protected]:~/ruby/hello$ cat bar.rb
class Foo
def initialize
puts "foo"
end
end
Foo.new
[email protected]:~/ruby/hello$
答
堆栈跟踪告诉你,你的require 'foo'
不能正常工作,因为它无法找到该文件foo.rb
。
这是因为require
将您给它的参数解释为绝对路径,或者它会在您的ruby加载路径中搜索指定的文件。
您可以通过提供文件的绝对路径来解决此问题。在这种情况下:require '/home/thufir/hello/foo'
将适用于您。
您也可以使用require_relative 'foo'
,它将在您的bar.rb
所在的目录中搜索文件foo.rb
。
https://ruby-doc.org/core-2.4.2/Kernel.html#method-i-require