Checking if a variable is defined?

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"

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.


The correct syntax for the above statement is:

if (defined?(var)).nil? # will now return true or false
 print "var is not definedn".color(:red)
else
 print "var is definedn".color(:green)
end

substituting ( var ) with your variable. This syntax will return a true/false value for evaluation in the if statement.

链接地址: http://www.djcxy.com/p/25764.html

上一篇: 设置名称存储在变量B中的变量A.

下一篇: 检查一个变量是否被定义?