我在 Ruby 中使用类继承变量来跟踪到目前为止我创建的实例的数量。为了保持我的代码 DRY,我在所有其他类都继承自的基类中实现了大部分逻辑。
class Entity
@instance_counter = 0
class << self
attr_accessor :instance_counter
end
def initialize
self.class.instance_counter += 1
end
end
这工作得很好,除了一件事:
我必须@instance_counter
在每个子类中定义,否则我会得到一个NoMethodError
.
class Child < Entity
@instance_counter = 0
end
有没有办法自动在每个孩子中声明变量,这样我就不必手动进行了?