Pet*_*ter 47 ruby metaprogramming local-variables
假设我正在使用irb
,并输入a = 5
.如何删除定义,a
以便键入a
返回NameError
?
一些背景:后来我想这样做:
context = Proc.new{}.binding
context.eval 'a = 5'
context.eval 'undef a' # though this doesn't work.
Run Code Online (Sandbox Code Playgroud)
mik*_*kej 47
有remove_class_variable,remove_instance_variable和remove_const方法,但目前没有局部变量的等价物.
Dan*_*iel 24
您可以通过减少变量存在的范围来避免取消声明变量:
def scope
yield
end
scope do
b = 1234
end
b # undefined local variable or method `b' for main:Object
Run Code Online (Sandbox Code Playgroud)
Dea*_*ffe 13
你总是可以通过调用一个irb子shell来"清除"irb的局部变量注册表.想想Bash shell如何处理未导出的环境变量.既然您提到了交互模式,那么这个解决方案应该可以解决这个问题.
就生产代码而言,我不想将局部变量取消定义为解决方案的一部分 - 对于那种类型的场景,键控散列可能更好.
这就是我的意思:
$ irb
irb(main):001:0> a = "a"
=> "a"
irb(main):002:0> defined? a
=> "local-variable"
irb(main):003:0> irb # step into subshell with its own locals
irb#1(main):001:0> defined? a
=> nil
irb#1(main):002:0> a
NameError: undefined local variable or method `a' for main:Object
from /Users/dean/.irbrc:108:in `method_missing'
from (irb#1):2
irb#1(main):003:0> exit
=> #<IRB::Irb: @context=#<IRB::Context:0x1011b48b8>, @signal_status=:IN_EVAL, @scanner=#<RubyLex:0x1011b3df0>>
irb(main):004:0> a # now we're back and a exists again
=> "a"
Run Code Online (Sandbox Code Playgroud)