【发布时间】:2010-09-25 02:45:46
【问题描述】:
这个问题最好用一个代码示例来概括:
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 包含 Bar。因此,当您在 Foo 上调用方法时,它会在 Bar 中查找该方法。
如果这是真的,那么在调用 TestTwo::Quux.new.foo 时,我已经将 foo 方法混合到 TestTwo::Bar 中,所以它应该可以工作,对吧?
【问题讨论】: