如何检查一个变量是否在Ruby中定义?是否有isset类型的方法可用?


当前回答

上述语句的正确语法是:

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

用变量替换(var)。该语法将返回一个true/false值,用于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

应该提到的是,使用defined来检查一个特定的字段是否在哈希中设置,可能会产生意想不到的行为:

var = {}
if defined? var['unknown']
  puts 'this is unexpected'
end
# will output "this is unexpected"

这里的语法是正确的,但定义?Var ['unknown']将被求值为字符串"method",因此if块将被执行

检查哈希中是否存在键的正确符号是:

if var.key?('unknown')

请注意“定义的”和“指定的”之间的区别。

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

X是定义的,即使它从未被赋值!

定义?(your_var)将工作。取决于你在做什么你也可以做your_var。nil?

使用定义的?YourVariable 保持简单,傻瓜..;)