Ruby 替换方法调用上的变量值
假设我有以下课程:Ruby 替换方法调用上的变量值,ruby,variables,methods,Ruby,Variables,Methods,假设我有以下课程: class MyClass @@instances = [] def initialize @@instances << self end#def def delete @@instances.delete(self) #what now?? self.replace nil #doesn't do the trick end#def end#class 执行delete时,o将为nil。有什么想法吗?正
class MyClass
@@instances = []
def initialize
@@instances << self
end#def
def delete
@@instances.delete(self)
#what now??
self.replace nil #doesn't do the trick
end#def
end#class
执行
delete
时,o
将为nil
。有什么想法吗?正如上面尤里卡所指出的,这是不可能做到的。但是,您可以实现类似的语义:
class MyClass
def delete
....
is_deleted
end
def is_deleted
check_some_conditions
end
end
然后,您的语法将是:
o = MyClass.new
if o.delete.is_deleted
...
end
您也可以重写
nil?
,但我不建议这样做,因为这可能会让使用您的代码的人感到困惑。如果您想获得MyClass
的所有实例的数组,您只需
ObjectSpace.each_object(MyClass).to_a
如果您想销毁MyClass
的o
实例,因为o
没有在其他地方引用,那么让o
引用其他内容
o = nil
稍后,对象将被垃圾收集。一种可能是:
vars = Kernel.global_variables + Kernel.local_variables
vars.map{|var| var=nil if var == self}
但是,我不认为这是一个聪明的办法
编辑:不,一点也不聪明这是不可能的:你只能修改对象本身,而不能修改对象本身,因为对象本身是对对象的引用,并且不能通过
delete
方法访问对象。@user1130886你是什么意思?对不起,只是习惯了在StackOverflow上写注释。我觉得我写的是答案而不是评论,很有趣。但是,仍然存在对该对象的引用,即使内核不知道它,也就是说,在执行上下文中。
vars = Kernel.global_variables + Kernel.local_variables
vars.map{|var| var=nil if var == self}