根类 Shipping 想要记录它的所有子类。但是当一个类 Grandchild 从 Shipping 的孩子继承时,就会发生错误。有人知道为什么会这样吗?先感谢您。
代码:
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
结果:
$ 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