从 array/hash 中删除仅从 array/hash 中引用的对象

Remove objects from array/hash which is only referenced from that array/hash

是否可以从仅从此 array/hash 引用的 array/hash 中删除对象?

我正在寻找的示例:

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 文件)的补丁,所以我无法使用。

您可以存储 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