Checking if a variable is defined?

Readonly picture Readonly · Nov 14, 2008 · Viewed 334.1k times · Source

How can I check whether a variable is defined in Ruby? Is there an isset-type method available?

Answer

Ricardo Acras picture Ricardo Acras · Nov 14, 2008

Use the defined? keyword (documentation). It will return a String with the kind of the item, or nil if it doesn’t exist.

>> a = 1
 => 1
>> defined? a
 => "local-variable"
>> defined? b
 => nil
>> defined? nil
 => "nil"
>> defined? String
 => "constant"
>> defined? 1
 => "expression"

As skalee commented: "It is worth noting that variable which is set to nil is initialized."

>> n = nil  
>> defined? n
 => "local-variable"