为什么在Ruby中包含模块的顺序会有所不同?
这个问题最好用一个代码示例来总结:为什么在Ruby中包含模块的顺序会有所不同?,ruby,include,module,Ruby,Include,Module,这个问题最好用一个代码示例来总结: 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 # =>
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)
我认为,当您在一个类Foo中包含一个模块(例如Bar)时,Ruby存储的所有内容都是Foo包含Bar的事实。所以,当您在Foo上调用一个方法时,它会在Bar中查找该方法
如果这是真的,那么在调用TestTwo::qux.new.foo时,我已经将foo方法混合到TestTwo::Bar中,所以它应该可以工作,对吗?文档说include调用的方法将方法混合到调用方中。因此,当TestTwo::Quux包含TestTwo::Bar时,不会向TestTwo::Quux添加任何方法。下一行将方法添加到TestTwo::Bar,但不添加到TestTwo::Quux。文档说,include调用的方法将方法混合到调用方中。因此,当TestTwo::Quux包含TestTwo::Bar时,不会向TestTwo::Quux添加任何方法。下一行将向TestTwo::Bar添加方法,但不向TestTwo::Quux添加方法。这是一个遗憾,因为在我的实际情况中,第一个包含发生在我无法控制的情况下,我只是尝试将一些东西混合到任何包含目标模块的东西中。啊,好吧,谢谢:这真是太遗憾了,因为在我的真实案例中,第一次包含发生在我无法控制的情况下,我只是试图将一些东西混合到任何包含我的目标模块的东西中。啊,谢谢: