如何计算 ruby 中一个类的现有实例? [英] How to count existing instances of a class in ruby?
问题描述
这是这个问题的一个想法:在创建对象时,增加一个类变量.当对象被收集时,减少它.如您所见,finalizer 被调用,并且 @@no_foo
被递减.但是当我稍后查询它时,减量消失了.似乎价值只会上升,永远不会下降(如果我创建两个对象,它将显示 2).我错过了什么明显的东西吗?
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 @@no_foo
gets decremented. But when I query it a moment later, decrement is gone. Seems that value is going only up, never down (if I create two objects, it will show 2). Am I missing something obvious?
class Foo
@@no_foo = 0
def initialize
puts 'creating object'
@@no_foo += 1
ObjectSpace.define_finalizer(self, proc { self.delete })
end
def delete
puts 'deleting object'
@@no_foo # => 1
@@no_foo -= 1
@@no_foo # => 0
end
def self.no_foo
@@no_foo # => 0, 1
end
end
Foo.no_foo # => 0
f = Foo.new
f = nil
GC.start
Foo.no_foo # => 1
# >> creating object
# >> deleting object
推荐答案
可以,但是finalization里面有循环引用.您的终结器取决于应收集的对象的绑定.请参阅此解决方案.
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
这篇关于如何计算 ruby 中一个类的现有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!