Testing for undefined variables in Ruby a la JavaScript?
-
23-08-2019 - |
Question
In JavaScript there's a useful way to test for a variable which has never been defined at any given point. For example, the following snippet of code will return true if the variable bob has not been defined:
typeof(bob)=='undefined'
How do I accomplish the same test in Ruby?
edit: I'm looking for a test which is equally compact in nature. I've come up with some awkward approximations using exceptions and such, but those aren't very pretty!
Solution
defined?(variable_name)
irb(main):004:0> defined?(foo)
=> nil
irb(main):005:0> foo = 1
=> 1
irb(main):006:0> defined?(foo)
=> "local-variable"
Here is a good write up on it.
OTHER TIPS
defined?
is a function that returns nil if the item is undefined.
defined? somevar
=> nil
somevar = 12
defined? somevar
=> "local-variable"
So:
if defined?(somevar)
do_something
end
Keep in mind that defined? returns a string if the variable is defined, nil if it isn't, so use conditional checking on its results. I think the syntax alludes that it would return a boolean.
All use cases :
defined? ur_variable
=> nil
ur_variable= 12
defined? ur_variable
=> "local-variable"
another_variable = nil
defined? another_variable
=> "local-variable"
Can also test this way.
if somevar.nil
# not set do something
else
# is set do something else
end