Checking if a variable is defined?
Solution 1:
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"
Solution 2:
This is useful if you want to do nothing if it does exist but create it if it doesn't exist.
def get_var
@var ||= SomeClass.new()
end
This only creates the new instance once. After that it just keeps returning the var.
Solution 3:
The correct syntax for the above statement is:
if (defined?(var)).nil? # will now return true or false
print "var is not defined\n".color(:red)
else
print "var is defined\n".color(:green)
end
substituting (var
) with your variable. This syntax will return a true/false value for evaluation in the if statement.
Solution 4:
defined?(your_var)
will work. Depending on what you're doing you can also do something like your_var.nil?
Solution 5:
Try "unless" instead of "if"
a = "apple"
# Note that b is not declared
c = nil
unless defined? a
puts "a is not defined"
end
unless defined? b
puts "b is not defined"
end
unless defined? c
puts "c is not defined"
end