这个问题最好用一个代码示例来概括:
module TestOne
module Foo
def foo
42
end
end
module Bar
include Foo
end
class Quux
include Bar
end
end
TestOne::Bar.ancestors # => [TestOne::Bar, TestOne::Foo]
TestOne::Quux.ancestors # => [TestOne::Quux, TestOne::Bar, TestOne::Foo, Object, Kernel]
TestOne::Quux.new.foo # => 42
module TestTwo
class Quux
end
module Bar
end
module Foo
def foo
42
end
end
end
TestTwo::Quux.send :include, TestTwo::Bar
TestTwo::Bar.send :include, TestTwo::Foo
TestTwo::Bar.ancestors # => [TestTwo::Bar, TestTwo::Foo]
TestTwo::Quux.ancestors # => [TestTwo::Quux, TestTwo::Bar, Object, Kernel]
TestTwo::Quux.new.foo # =>
# ~> -:40: undefined method `foo' for #<TestTwo::Quux:0x24054> (NoMethodError)
我认为当你包含一个模块时(例如。
Bar
在课堂内
Foo
)Ruby存储的只是这样一个事实
Foo
包括
酒吧
因此,当你在Foo上调用一个方法时,它看起来
酒吧
对于该方法。
如果这是真的,到那时
TestTwo::Quux.new.foo
被称为我混合了
foo
方法进入
TestTwo::Bar
所以它应该奏效,对吧?