Ruby继承链

657 查看

module M1
end

module M2
end

module M3
end

module M4
end

class Hello
  include M1
  include M2

  # This is the position of class self

  prepend M3
  prepend M4
end

p Hello.ancestors
# M4, M3, Hello, M2, M1, Object, Kernel, BasicObject

列出类继承链的技巧:

  1. include 的模块按顺序排在上面部分

  2. prepend 的模块按顺序排在下面部分

  3. 将类本身放在 includeprepend 的中间位置

  4. 继承顺序就是从下往上数,包括类本身