[英]Ruby hook method inherited related - Why @children changed to nil?
The root class Shipping want to record all its children. 根类Shipping希望记录其所有子项。 But when a class Grandchild inherit from Shipping's child ,error occurs.Does somebody know why this happens? 但是,当一个孙子类继承自Shipping的孩子时,会发生错误。有人知道为什么会这样吗? Thank you in advance. 先感谢您。
code: 码:
class Shipping
@children = []
def self.inherited(child)
puts "#{child.name} inherit Shipping"
@children << child
end
def self.show_children
p @children
end
end
class Child1 < Shipping
end
class Child2 < Shipping
end
class Grandchild < Child2
end
Shipping.show_children
result: 结果:
$ jruby temptry.rb
Child1 inherit Shipping
Child2 inherit Shipping
Grandchild inherit Shipping
NoMethodError: undefined method `<<' for nil:NilClass
inherited at temptry.rb:5
(root) at temptry.rb:18
When a class inherits another one, the methods are inherited, but a class instance variable is not particularly initialized. 当一个类继承另一个类时,方法将被继承,但是类实例变量并未特别初始化。 You only initialized @children
for Shipping
, but did not do it for Grandchild
. 你只初始化@children
的Shipping
,但并没有这样做Grandchild
。
If you want to share a variable between inherited classes, then you should be using a class variable. 如果要在继承的类之间共享变量,则应使用类变量。 If you do: 如果您这样做:
class Shipping
@@children = []
...
end
and change all @children
to @@children
, then they will be shared. 并将所有@children
更改为@@children
,然后将它们共享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.