用 ruby 实例化 Foo?

instantiate Foo with ruby?

如何从 bar.rb instantiate Foo?

# foo.rb
class Foo
  def initialize
    puts "foo"
  end
end
# bar.rb
require 'foo'

Foo.new
$ 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>'

目前不使用模块。在同一脚本中声明 Foo 时工作正常:

# bar.rb with Foo declared inside
class Foo
  def initialize
    puts "foo"
  end
end

Foo.new
$ ruby bar.rb 
foo

堆栈跟踪告诉您,您的 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