Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefine variable in Ruby

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?

Some context: later I want to do this:

context = Proc.new{}.binding context.eval 'a = 5' context.eval 'undef a'  # though this doesn't work. 
like image 902
Peter Avatar asked Jan 06 '10 08:01

Peter


People also ask

Can we Undefine a method in Ruby?

Ruby provides a special keyword which is known as undef keyword. This keyword used to avoid the current working class from responding to calls to the specified named methods or variable. Or in other words, once you use under keyword with any method name you are not able to call that method.

How do you delete a variable in ruby?

We use the delete() method to delete an environment variable in Ruby. Environment variables are used to share configuration options between all the programs in our system.

What is undefined in Ruby?

The undefined method is also called the NoMethodError exception, and it's the most common error within projects, according to The 2022 Airbrake Error Data Report. It occurs when a receiver (an object) receives a method that does not exist.


2 Answers

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

like image 59
mikej Avatar answered Sep 22 '22 01:09

mikej


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

def scope    yield end  scope do    b = 1234 end  b  # undefined local variable or method `b' for main:Object 
like image 38
Daniel Avatar answered Sep 19 '22 01:09

Daniel