title: Deleting an object in Ruby
body: <p>Let's say I have the following class:</p>
  
  <pre><code>class Vehicle
      @@total_vehicles = 0
      @@all_instances = Array.new
  
      def initialize
          @@total_vehicles += 1
          @@all_instances &lt;&lt; self
      end
  
      def total_vehicles #returns total number of Vehicles 'alive'
          return @@total_vehicles
      end
  
      def all_vehicles #returns an array of all Vehicle objects
          return @@all_instances
      end
  
  end
  </code></pre>
  
  <p>Now to keep <code>@@total_vehicles</code> and <code>@@all_instances</code> up-to-date and correct, I want to make sure that they are correctly decremented and updated, respectively, when one of those objects is garbage collected. But here is what happens:</p>
  
  <pre><code>v = Vehicle.new
  Vehicle.total_vehicles # =&gt; 1
  v = nil #no references to Vehicle instance now
  ObjectSpace.garbage_collect #instance garbage collected
  Vehicle.total_vehicles # =&gt; 1    Nope!
  </code></pre>
  
  <p>Well I could add a finalizer Proc to each instance of the Vehicle class that, when called upon the object's garbage collection, would be called. But according to the documentation, <code>ObjectSpace.define_finalizer(v,someProc)</code> would call someProc <em>after</em> the Vehicle instance is destroyed - meaning I cannot use <code>self</code> or <code>self.class</code> in there (since there would be no class, as there is no object!) I could have the proc call a public accessor method on the Vehicle class, but that takes away the purpose of class variables being accessible only to the class and its instances -> essentially turning the class variables into gvars.</p>
  
  <p>How can I have the equivalent of a destructor method (from C++) that will get a Vehicle instance's affairs in order, as it were, before getting garbage-collected?</p>
  
  <p>P.S.
  <code>ObjectSpace#count_objects</code> is no a viable option, as even the Ruby docs are up front about.</p>