[英]Ruby hook method inherited related - Why @children changed to nil?
根類Shipping希望記錄其所有子項。 但是,當一個孫子類繼承自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
當一個類繼承另一個類時,方法將被繼承,但是類實例變量並未特別初始化。 你只初始化@children
的Shipping
,但並沒有這樣做Grandchild
。
如果要在繼承的類之間共享變量,則應使用類變量。 如果您這樣做:
class Shipping
@@children = []
...
end
並將所有@children
更改為@@children
,然后將它們共享。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.