代码之家  ›  专栏  ›  技术社区  ›  Peter

在Ruby中取消定义变量

  •  44
  • Peter  · 技术社区  · 15 年前

    假设我正在使用 irb 和类型 a = 5 . 如何删除 a 所以打字 返回A NameError ?

    一些背景:稍后我想这样做:

    context = Proc.new{}.binding
    context.eval 'a = 5'
    context.eval 'undef a'  # though this doesn't work.
    
    5 回复  |  直到 6 年前
        1
  •  44
  •   Victor lest    6 年前

    remove_class_variable , remove_instance_variable remove_const 方法,但目前没有等价的局部变量。

        2
  •  21
  •   Daniel    10 年前

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

    def scope 
      yield
    end
    
    scope do 
      b = 1234
    end
    
    b  # undefined local variable or method `b' for main:Object
    
        3
  •  13
  •   Dean Radcliffe    14 年前

    您可以通过调用IRB子外壳来“清除”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"
    
        4
  •  0
  •   Nakul    15 年前

    目前,您没有删除全局变量、局部变量和类变量的方法。但是,可以使用“remove-const”方法删除常量

        5
  •  0
  •   RWDJ    6 年前

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

    我唯一能想到的办法就是 Integer#times Array#each 就像这样:

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

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