为什么包含模块的顺序在Ruby中有所不同?

时间:2008-12-03 12:10:50

标签: 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 # => [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中,所以它应该有效,对吗?

1 个答案:

答案 0 :(得分:3)

文档说append_features(由include调用)将方法混合到调用者中。因此,当TestTwo::Quux包含TestTwo::Bar时,TestTwo::Quux不会添加任何方法。下一行将方法添加到TestTwo::Bar,但不添加到TestTwo::Quux

相关问题