Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中的未定义变量_Ruby_Metaprogramming_Local Variables - Fatal编程技术网

Ruby中的未定义变量

Ruby中的未定义变量,ruby,metaprogramming,local-variables,Ruby,Metaprogramming,Local Variables,假设我使用的是irb,输入a=5。如何删除a的定义,以便键入a返回namererror 一些上下文:稍后我想做以下操作: context = Proc.new{}.binding context.eval 'a = 5' context.eval 'undef a' # though this doesn't work. 目前,您没有删除全局变量、局部变量和类变量的方法。您可以使用“remove_const”方法删除常量,虽然有,但目前没有本地变量的等效方法。您可以通过调用irb子shell

假设我使用的是
irb
,输入
a=5
。如何删除
a
的定义,以便键入
a
返回
namererror

一些上下文:稍后我想做以下操作:

context = Proc.new{}.binding
context.eval 'a = 5'
context.eval 'undef a'  # though this doesn't work.

目前,您没有删除全局变量、局部变量和类变量的方法。您可以使用“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"
$irb
irb(主):001:0>a=“a”
=>“a”
irb(主):002:0>已定义?A.
=>“局部变量”
irb(main):003:0>irb#与自己的本地人一起进入子shell
irb#1(主要):001:0>定义?A.
=>零
irb#1(主要):002:0>a
NameError:未定义的局部变量或main:Object的方法“a”
from/Users/dean/.irbrc:108:in'method_missing'
来自(irb#1):2
irb#1(主):003:0>退出
=> #
irb(main):004:0>a#现在我们回来了,a再次存在
=>“a”

通过缩小变量存在的范围,可以避免取消声明变量:

def scope 
  yield
end

scope do 
  b = 1234
end

b  # undefined local variable or method `b' for main:Object

根据问题的精神,您可以将变量限制在一个范围内,假设您同意将其他局部变量锁定在同一范围内。如果您在类中定义某些内容,并且不希望局部变量停留在类声明中,这一点尤其有用

我能想到的唯一方法是使用
整数#倍
数组#每个
如下:

1.times do |a|
  a = 5
  # code…
end

[5].each do |a|
  # code…
end

除此之外,可能还有其他更干净的方法来限制一个街区。这些没有我想要的那么干净,我想看看是否有人有更干净的方法来做这件事。

对于类变量不是这样的-有remove\u class\u variable.hmm,令人恼火的是没有这样的方法。我想我现在可以继续使用实例变量。这些链接看起来不再指向正确的位置了。@jcollum谢谢
remove_instance_variable
remove_const
都是私有方法,因此ruby-doc.org上的文档中似乎不再包含这些方法。我已经更新了答案,使用到apidock.com的等效链接。这是我想要看到的答案。有一种标准的
scope
函数称为
Proc.new
Proc.new{b=1};b
值得注意的是,
Proc.new
与给定的
范围
不同之处在于它实际上不调用块。等价物是
Proc.new{b=1}.call;b
。您还可以使用
lambda{b=1}.call
。它返回:“
NotImplementedError:ruby引擎只能在主线程中初始化