Tag: 终结器

删除对象时运行方法

我正在学习ruby并且没有找到覆盖等效object.delete函数的方法: 这就是我这样做的方式: 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 正如你所看到的,这是处理事情的一种hacky方式……有没有更简单的方法来解决这个问题? 基本上我想在减少该类的总计数器的同一调用中使我的对象无法访问。 在将变量(指向对象的指针)设置为nil时,我找不到一个被调用的方法。 我发现无法删除对象。

删除Ruby中的对象

假设我有以下课程: class Vehicle @@total_vehicles = 0 @@all_instances = Array.new def initialize @@total_vehicles += 1 @@all_instances << self end def total_vehicles #returns total number of Vehicles 'alive' return @@total_vehicles end def all_vehicles #returns an array of all Vehicle objects return @@all_instances end end 现在让@@total_vehicles和@@all_instances保持最新和正确,我想确保在其中一个对象被垃圾收集时分别正确地减少和更新它们。 但这是发生的事情: v = Vehicle.new Vehicle.total_vehicles # => 1 v = nil #no […]