The following class Point
contains a class instance variable @count
that counts the number of instances created. It seems to work fine:
class Point @count = 0 class << self attr_accessor :count end def initialize(position) @position = position self.class.count += 1 endend
However, if I add a subclass ColoredPoint
and I want @count
to include the number of these created too:
class ColoredPoint < Point def initialize(position, color) super(position) @color = color endend
This gives an error when calling ColoredPoint.new(1, 'red')
:
undefined method '+' for nil (NoMethodError) self.class.count += 1
How can I make this work? Do I have to use a class variable (@@count
), even though I've read that "you should avoid them at all costs"?