How to unset a variable in ruby

hi,

$a=23

def function

puts $a

end

Now I need to unset this variable, how would I do this? That means that
variable no longer should be in use. Can anyone please provide me the
solution for this?

RAJ

$a = nil

Or if you don’t use a global variable, once it’s out of scope it will be
garbage collected.

hi,

If you assign the value nil, then it’s still holding the object, $a or a
still is in use, I would like to undefine the variable,which means If
you use the variable again, program has to say “undefined local variable
or method `a’ for main:Object (NameError)”, How would I do this?

RAJ

Why do you need to assigne a value to a global variable when you don’t
need it later in your program? Such code really smells. You should
rather find a better place for it (maybe a local or instance variable)
in your code and let the garbage collector take care of it once it’s
done its job.

hi,

Yes as you say I could have used local variable, but I need the same
variable within more than one function and that’s the reason I am in a
need of deleting that variable after usage.

hi Damián M. González

Ok, thank you.

The answer is that global variables by default have nil value. If you
are specting Ruby to throw an error because of a global variable was
never set you are thinking wrong, whatever call to a global variable
will return nil if not defined, so don’t worry. If you want to free
memory just assing nil to the global variable you don’t need anymore.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs