Testing for undefined variables in Ruby a la JavaScript?

Maciek picture Maciek · May 20, 2009 · Viewed 16.5k times · Source

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!

Answer

jshen picture jshen · May 20, 2009
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.