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


当前回答

试着用“除非”而不是“如果”

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

其他回答

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

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

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

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

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

试着用“除非”而不是“如果”

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

正如许多其他示例所示,在ruby中,实际上不需要从方法中获取布尔值来进行逻辑选择。除非你真的需要一个布尔值,否则把所有东西都强制转换成布尔值是一种糟糕的形式。

但如果你确实需要一个布尔值。使用! !(bang bang)或者“falsy falsy揭示真相”。

› irb
>> a = nil
=> nil
>> defined?(a)
=> "local-variable"
>> defined?(b)
=> nil
>> !!defined?(a)
=> true
>> !!defined?(b)
=> false

为什么强迫通常不划算:

>> (!!defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red)) == (defined?(a) ? "var is defined".colorize(:green) : "var is not defined".colorize(:red))
=> true

这里有一个重要的例子,因为它依赖于布尔值对其字符串表示的隐式强制。

>> puts "var is defined? #{!!defined?(a)} vs #{defined?(a)}"
var is defined? true vs local-variable
=> nil