简体   繁体   中英

Ruby hook method inherited related - Why @children changed to nil?

The root class Shipping want to record all its children. But when a class Grandchild inherit from Shipping's child ,error occurs.Does somebody know why this happens? 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM