假設我正在使用irb
,並輸入a = 5
。如何刪除a
的定義,以便打字a
返回NameError
?Ruby中的未定義變量
一些背景:以後我想這樣做:
context = Proc.new{}.binding
context.eval 'a = 5'
context.eval 'undef a' # though this doesn't work.
假設我正在使用irb
,並輸入a = 5
。如何刪除a
的定義,以便打字a
返回NameError
?Ruby中的未定義變量
一些背景:以後我想這樣做:
context = Proc.new{}.binding
context.eval 'a = 5'
context.eval 'undef a' # though this doesn't work.
有remove_class_variable,remove_instance_variable和remove_const方法,但目前沒有等效的局部變量。
您可以通過調用一個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"
您可以通過減少其中的變量存在的範圍避免未聲明的變量:
def scope
yield
end
scope do
b = 1234
end
b # undefined local variable or method `b' for main:Object
這是我想看到的答案。 – 2014-12-14 15:05:35
嗯,惱人的是,沒有任何這樣的方法。我想我現在可以堅持實例變量。 – Peter 2010-01-06 20:43:55
這些鏈接看起來不像他們要去的地方了。 – jcollum 2012-01-16 22:53:27
@jcollum謝謝。 'remove_instance_variable'和'remove_const'是私有方法,所以似乎不再包含在ruby-doc.org的文檔中。我更新了答案,使用等效鏈接到apidock.com – mikej 2012-01-17 17:32:29