Checking if a variable is defined?

2019-01-04 15:23发布

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

14条回答
【Aperson】
2楼-- · 2019-01-04 16:04

Use defined? YourVariable
Keep it simple silly .. ;)

查看更多
Explosion°爆炸
3楼-- · 2019-01-04 16:06

You can try:

unless defined?(var)
  #ruby code goes here
end
=> true

Because it returns a boolean.

查看更多
家丑人穷心不美
4楼-- · 2019-01-04 16:12

Please note the distinction between "defined" and "assigned".

$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"

x is defined even though it is never assigned!

查看更多
Animai°情兽
5楼-- · 2019-01-04 16:13

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
查看更多
Viruses.
6楼-- · 2019-01-04 16:16

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"
查看更多
淡お忘
7楼-- · 2019-01-04 16:17

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.

查看更多
登录 后发表回答