2017-10-28 163 views
0

我如何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$ 

回答

2

堆棧跟蹤告訴你,你的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