根据 Dave Thomas 在他关于 Ruby 对象模型的演讲中,Ruby中没有“类方法”。方法的接收者是“类对象”还是“实例对象”只有区别。
class Dave
def InstaceMethod ### will be stored in the current class (Dave)
puts "Hi"
end
class << self ### Creates an eigenclass, if not created before
def say_hello
puts "Hello"
end
end
end
默认情况下,ancestors
方法不显示元类:
class Dave
class << self
def metaclass ### A way to show the hidden eigenclass
class << self; self; end
end
end
end
p Dave.ancestors
# => [Dave, Object, Kernel, BasicObject]
p Dave.metaclass.ancestors
# => [Class, Module, Object, Kernel, BasicObject]
但是,我认为真正的应该是这样的:
# => [<eigenclass>, Class, Module, Object, Kernel, BasicObject]
p Dave.class.instance_method(false)
# => [:allocate, :new, :superclass]
p Dave.metaclass.instance_method(false)
# => [:say_hello, :metaclass]
现在继承。
class B < Dave
end
p B.say_hello
# => "Hello"
p B.ancestors
# => [B, Dave, Object, Kernel, BasicObject]
p B.class.instance_methods(false)
# => [:allocate, :new, :superclass]
以下将为 创建一个新的特征类B
:
p B.metaclass.ancestors
# => [Class, Module, Object, Kernel, BasicObject]
p B.metaclass.instance_method(false)
# => []
当特征类也包括在内时 和 会是什么样
B.ancestors
子?B.metaclass.ancestors
该方法say_hello
存储在一个特征类中,(我假设B.class
继承自)但那在哪里?由于有两个祖先链(
B.ancestors
和B.class.ancestors
或B.metaclass.ancestors
),继承实际上是如何发生的?