views:

851

answers:

3

Hi,

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!

+9  A: 
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.

jshen
heheh, who would have known it would be so easy. I was doing stuff like:test = begin does_not_existrescue NameError "undefined"end
Corban Brook
interesting that defined? blah returns nil and not false and returns a string of type if it is defined
Corban Brook
There are some other options like object.instance_variable_defined?(:var_name). Search in the docs for defined? and you'll find the more specific versions.
jshen
nil is falsey. You can do 'if defined?(blah)'
jshen
I realize this just seems strange because of '?' at the end of the method. I would assume a boolean return but instead get nil or a string
Corban Brook
+4  A: 

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
Tim Sullivan
+1  A: 

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.

Andrew Noyes
True, but since 'nil' is falsey and all strings are truthy, you can treat the return values like booleans for all flow-control purposes (if, elsif, unless, while, until, etc).
rampion