包含类方法和继承的Ruby模块

包含类方法和继承的Ruby模块,ruby,Ruby,我很难理解为什么以下方法不起作用: module M1 def m1 p 'm1' end module ClassMethods def m1c p 'm1c' end end def self.included base base.extend ClassMethods end end module M2 include M1 def m2 p 'm2' end end class Foo

我很难理解为什么以下方法不起作用:

module M1
  def m1
    p 'm1'
  end

  module ClassMethods
    def m1c
      p 'm1c'
    end
  end

  def self.included base
    base.extend ClassMethods
  end
end

module M2
  include M1

  def m2
    p 'm2'
  end
end


class Foo
  include M2

  def hi
    p 'hi'
  end
end

Foo.new.hi => 'hi'
Foo.new.m1 => 'm1'
Foo.new.m2 => 'm2'
Foo.m1c => undefined method `m1c' for Foo:Class (NoMethodError)

如果我将
M1
直接包含在
Foo
中,那么所有方法都会按预期工作,但似乎要将其包含在
M2
中。我是否误解了模块?

当您在
M2
中包含M1时,
M1
的实例方法以及来自
ClassMethods
的类方法被合并到
M2
中,因为
本身包含了
定义


但是当您在
Foo
包含M2
时,您只包含
M2
的实例方法。
M2
的类方法未合并到
Foo

中,谢谢!我在想每次包含时都会调用
included
钩子,但为什么只有在
M2
中包含钩子时才会调用钩子才有意义;base.extend;分类方法;结束
M2
和鲍勃的叔叔。