我知道我可以通过 Kernel#global_variables 查看所有全局变量,但是有没有类似于 remove_instance_variable、remove_class_variable、remove_const 方法的方法来删除它们?或者有没有办法使用它们来完成同样的事情?
最佳答案
我不相信可以“取消设置”一个全局变量。最好的办法是将变量设置为 nil
。
通常,当您尝试使用尚 undefined variable 时,Ruby 会抛出错误。
irb > "The following variable has not yet been defined: #{a}"
irb > NameError: undefined local variable or method `a' for main:Object
这种行为实际上与全局变量不同。任何调用尚未定义的全局变量的尝试都将返回 nil
。
irb > "The following global variable has not yet been defined: #{$a}"
# => The following global variable has not yet been defined:
irb > $a.class
# => NilClass
因此,将全局变量设置为 nil 应该具有与“取消设置”它所期望的完全相同的行为。
关于ruby - 在 Ruby 中删除全局变量的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8102389/