How can I check whether a variable is defined in Ruby? Is there an isset
-type method available?
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"