我正在寻找的例子:
some_array.reject!{|elm| ObjectSpace.only_one_reference_to?(elm)}
我正在编写一个似乎在ram中快速增长的脚本。原因在于它是一个长寿命的数组,它可以在事件周围保留过时的对象,尽管它不需要。
问题基本上是这样的:
@@long_living_array = []
class Foo
def initialize
@@long_living_array << self
end
end
a = Foo.new()
b = Foo.new()
a = nil
#Here is the problem, a sticks around in @@long_living_array, even though it does not really need to be there.
因此,我的真正任务是迭代@@long_living_array
并删除任何仅从此数组引用的对象。 (是的,我确实需要阵列。)
我相信如果我能找到对象的所有引用,然后在数组中的引用是唯一的引用时删除对象,就可以解决它。因此,我一直在寻找
的内容a = Foo.new
all_references_to_a = ObjectSpace.get_all_references(a)
我发现this article似乎做了类似的事情,但它是Ruby本身的补丁(一些C文件)所以我无法使用它。
答案 0 :(得分:2)
您可以存储WeakRef
,而不是存储对象本身。它允许引用的对象被垃圾收集:
require 'weakref'
@@long_living_array = []
class Foo
def initialize
@@long_living_array << WeakRef.new(self)
end
end
a = Foo.new
b = Foo.new
@@long_living_array.count
#=> 2
a = nil # reassign 'a'
GC.start # start the garbage collector
@@long_living_array.keep_if(&:weakref_alive?) # remove GC'ed objects
@@long_living_array.count
#=> 1