patternrubyCritical
Checking if a variable is defined?
Viewed 0 times
definedvariablechecking
Problem
How can I check whether a variable is defined in Ruby? Is there an
isset-type method available?Solution
Use the
As skalee commented: "It is worth noting that variable which is set to nil is initialized."
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"Code Snippets
>> a = 1
=> 1
>> defined? a
=> "local-variable"
>> defined? b
=> nil
>> defined? nil
=> "nil"
>> defined? String
=> "constant"
>> defined? 1
=> "expression">> n = nil
>> defined? n
=> "local-variable"Context
Stack Overflow Q#288715, score: 823
Revisions (0)
No revisions yet.