如何从模块中定义的类扩展ruby类?

slu*_*her 6 ruby

我有以下文件:

file.rb

require_relative 'foo/bar'
baz = Foo::Stuff::Baz.new
# do stuff
Run Code Online (Sandbox Code Playgroud)

富/ bar.rb

require_relative 'stuff/baz'
module Foo
    class Bar
        def initialize
            # do stuff
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

富/材料/ baz.rb

module Foo
    module Stuff
        class Baz < Bar
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

`':未初始化的常量Foo :: Stuff :: Bar(NameError)

我有什么问题吗?这在Ruby中是否可行?如果它很重要,我只是这样做,因为我需要专门继承initialize方法.

Eri*_*nil 3

当你把它们放在同一个脚本中时它工作得很好:

module Foo
  class Bar
    def initialize
      # do stuff
    end
  end
end

module Foo
  module Stuff
    class Baz < Bar
    end
  end
end

p Foo::Stuff::Baz.ancestors
#=> [Foo::Stuff::Baz, Foo::Bar, Object, Kernel, BasicObject]
Run Code Online (Sandbox Code Playgroud)

因此,这一定是您需要文件的方式或顺序有问题。

另外,如果您只需要Foo::Barin中的一个特定方法Foo::Stuff::Baz,您可以将该方法放入一个模块中,并在两个类中都包含该模块。