title: How to declare Class Instance Variable in inherited class automatically
body: <p>I am using Class Inheritance Variables in Ruby to keep track of the number of instances I've created so far. To keep my code DRY, I implemented most of the logic in a base class that all my other classes inherit from.</p>
  
  <pre><code>class Entity
    @instance_counter = 0
  
    class &lt;&lt; self
      attr_accessor :instance_counter
    end
  
    def initialize
      self.class.instance_counter += 1
    end
  end
  </code></pre>
  
  <p>This works perfectly fine except for one thing:</p>
  
  <p>I have to define <code>@instance_counter</code> in each child class, or I will get an <code>NoMethodError</code>.</p>
  
  <pre><code>class Child &lt; Entity
    @instance_counter = 0
  end
  </code></pre>
  
  <p>Is there a way to declare the variable in each child automatically so that I don't have to do it manually?</p>