Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4627

In Ruby, how to count the number of instances created (including subclasses)?

$
0
0

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"?


Viewing all articles
Browse latest Browse all 4627

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>