Here\'s an idea from this question: Upon object creation, increment a class variable. When object gets collected, decrement it. As you can observe, finalizer is called, and
It can work, but there's circular reference in finalization. Your finalizer depends on the binding of an object that should be collected. See this solution.
class Foo
@@no_foo = 0
def initialize
@@no_foo += 1
ObjectSpace.define_finalizer(self, Foo.method(:delete))
end
def self.delete id # also this argument seems to be necessary
@@no_foo -= 1
end
def self.no_foo
@@no_foo
end
end
Foo.no_foo # => 0
1000.times{Foo.new}
Foo.no_foo # => 1000
GC.start
Foo.no_foo # => 0