How to count existing instances of a class in ruby?

前端 未结 2 583
孤城傲影
孤城傲影 2020-12-18 10:17

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

2条回答
  •  太阳男子
    2020-12-18 10:53

    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
    

提交回复
热议问题