代码之家  ›  专栏  ›  技术社区  ›  Gareth

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

  •  2
  • Gareth  · 技术社区  · 17 年前

    这个问题最好用一个代码示例来概括:

    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 所以它应该奏效,对吧?

    1 回复  |  直到 17 年前
        1
  •  4
  •   Matt Burke    17 年前

    医生说 append_features (由include调用)将方法混合到调用者中。所以什么时候 TestTwo::Quux 包括 TestTwo::Bar ,未添加任何方法 测试二:Quux 。下一行添加了以下方法 测试二::酒吧 ,但不是 测试二:Quux .