1

この質問は、コード例で最もよく要約されます。

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クラス内に)含めると、Rubyが格納するのは。を含むFooという事実だけだと思いました。したがって、Fooでメソッドを呼び出すと、そのメソッドが検索されます。FooBarBar

それが本当なら、その時TestTwo::Quux.new.fooまでに私はfooメソッドを混ぜ合わせたTestTwo::Barので、うまくいくはずですよね?

4

1 に答える 1

4

ドキュメントによると、append_features(includeによって呼び出される)はメソッドを呼び出し元に混合します。したがって、TestTwo::QuuxincludesTestTwo::Barの場合、メソッドはに追加されませんTestTwo::Quux。次の行では、メソッドをTestTwo::Barに追加していますが、には追加していませんTestTwo::Quux

于 2008-12-03T13:23:09.993 に答える