根據戴夫托馬斯在his talk about the Ruby Object Model,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]
下會創建一個新的eigenclass爲B
:
p B.metaclass.ancestors
# => [Class, Module, Object, Kernel, BasicObject]
p B.metaclass.instance_method(false)
# => []
將如何
B.ancestors
和B.metaclass.ancestors
的樣子時,也被包括在eigenclasses?方法say_hello
存儲在本徵類(我假設B.class
繼承自),但它在哪裏?由於有兩個祖先鏈(
B.ancestors
和B.class.ancestors
或B.metaclass.ancestors
),繼承是如何發生的?