使用类变量保存 subclass 是没问题的:
class Base
@@a = []
def self.inherited(subclass)
puts "subclass = #{subclass}"
@@a << subclass
end
def self.out
p @@a
end
end
class C1 < Base
end
class D < C1
end
Base.out
Base.out 输出为: subclass = C1 subclass = D [C1, D]
但我改成类实例变量,就会报错:
class Base
@list = []
def self.inherited(subclass)
puts "subclass = #{subclass}"
@list << subclass
end
def self.out
p @list
end
end
class C1 < Base
end
class D < C1
end
Base.out
subclass = C1
subclass = D
1.rb:7:in inherited': undefined method
<<' for nil:NilClass (NoMethodError)
from 1.rb:19:in `
但若是将 class D < Base 时,再执行 Base.out 就不报错,输出正确了。 为什么 class D < C1 时,会报错呢?