ruby - 在 Ruby 中删除全局变量的方法?

标签 ruby global-variables

我知道我可以通过 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/

相关文章:

ios - 具有全局变量的共享实例

c - 在 C 中试验全局变量和函数

ruby - Ruby 中的奇怪之处

ruby - 将结果传递给 redis 中的另一个命令

ruby - 使用 Nokogiri 拆分 BR 标签上的内容

python - 在 Python 中将列表定义为全局变量

c - 通过 extern 使用全局变量时两害相权取其轻

c - 全局变量链接行为

Ruby - 从电子邮件地址中查找文本中的名字和姓氏

ruby - 删除 HTML 标签的正则表达式问题