在删除对象时运行方法 [英] Run a Method on deletion of an Object
问题描述
我正在学习 ruby 并且还没有找到一种方法来覆盖等效的 object.delete
函数:
I am learning ruby and haven't found a way to override an equivalent object.delete
function:
我是这样做的:
class Foo
@@no_foo=0
def initialize
@@no_foo+=1
end
def delete
#class specific cleanup...
@@no_foo-=1
end
def Foo.no_foo
return "#@@no_foo"
end
end
def delete(obj)
#object independent cleanup...
obj.delete
return nil
end
foo1 = Foo.new
foo2 = Foo.new
puts Foo.no_foo
puts foo2
foo2 = delete(foo2)
puts foo2
puts Foo.no_foo
如您所见,这种处理方式有点古怪...有没有更简单的方法来解决这个问题?
基本上,我想让我的对象在减少该类的总计数器的同一个调用中无法访问.我找不到在将变量(指向对象的指针)设置为 nil 时调用的方法.
As you can see, this is a bit of a hacky way of going about things...
is there an easier way to go about this?
Basically I would like to make my objects unaccessible in the same call as decrementing the total counter for that class.
I couldn't find a method that gets called when setting a variable(pointer to object) to nil.
我发现无法删除对象.
推荐答案
根据@RubyLovely 提供的链接:WeakRef.
我整理了以下示例类:
as per the link provided by @RubyLovely: WeakRef.
I put together the following sample class:
require 'weakref'
class Foo
#block to excecute on GC.start...
FINALIZER = lambda { |object_id| p "finalizing %d" % object_id; @@no_foo -=1 }
@@no_foo=0
def initialize
@@no_foo+=1
#Initialising the finalizer...
ObjectSpace.define_finalizer(self, FINALIZER)
end
def Foo.no_foo
@@no_foo
end
end
foo = Foo.new
foo = WeakRef.new(foo)
puts Foo.no_foo
GC.start
puts Foo.no_foo
这篇关于在删除对象时运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!