Undefine variable in Ruby

后端 未结 5 1257
迷失自我
迷失自我 2020-12-05 06:29

Let\'s say I\'m using irb, and type a = 5. How do I remove the definition of a so that typing a returns a NameError

5条回答
  •  再見小時候
    2020-12-05 06:46

    You can always 'clear' irb's registry of local variables by invoking an irb subshell. Think of how Bash shells work with respect to unexported environment variables. Since you metioned interactive mode, this solution ought to work for that.

    As far as production code, I wouldn't want to undefine local variables as part of a solution - keyed hashes would probably be better for that type of scenario.

    Here's what I mean:

    $ 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
    => #, @signal_status=:IN_EVAL, @scanner=#>
    irb(main):004:0> a # now we're back and a exists again
    => "a"
    

提交回复
热议问题