我已经建立了两个类如下图所示红宝石继承和重写类方法
class Parent
def self.inherited(child)
child.custom_class_method
end
def self.custom_class_method
raise "You haven't implemented me yet!"
end
end
class Child < Parent
def self.custom_class_method
"hello world"
end
end
看来,当的传承Child < Parent
评估,它调用self.inherited
,这又引发了self.custom_class_method
的Parent
的版本而不是Child
的。这是因为,而不是让问题预期"hello world"
我得到一个错误募说"You haven't implemented me yet!"
不Child
的,直到后self.custom_class_method
没有得到评估Parent
的self.inherited
完成评估?如果是的话,那么可能是围绕这个做了一个工作?我是不是应该在父类上放一个raise
检查?
这似乎很奇怪。获得父类的'custom_class_method'的唯一方法应该是调用'super'。否则,只调用'Child.custom_class_method'应该会导致您的“hello world”输出。你能否提供更深入的日志记录? –
嗯,我同意它应该!但似乎我可以通过将代码块复制粘贴到“irb”控制台来复制此内容。由于这个原因,评估“Child”类时会出错。 – aMat