Undefine variable in Ruby Undefine variable in Ruby ruby ruby

Undefine variable in Ruby


There are remove_class_variable, remove_instance_variable and remove_const methods but there is currently no equivalent for local variables.


You can avoid un-declaring the variable by reducing the scope in which the variable exists:

def scope   yieldendscope do   b = 1234endb  # undefined local variable or method `b' for main:Object


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:

$ irbirb(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 localsirb#1(main):001:0> defined? a=> nilirb#1(main):002:0> aNameError: undefined local variable or method `a' for main:Object    from /Users/dean/.irbrc:108:in `method_missing'    from (irb#1):2irb#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"