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


当前回答

此外,你可以检查它是否通过插值在字符串中定义,如果你编码:

puts "Is array1 defined and what type is it? #{defined?(@array1)}"

如果定义了类型,系统会告诉您。 如果没有定义,它将返回一个警告,说变量没有初始化。

希望这能有所帮助!:)

其他回答

留下一个非常简单的例子,以防有用。

当变量不存在时:

if defined? a then "hi" end
# => nil

当变量存在时:

a = 2
if defined? a then "hi" end
# => "hi"

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

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

你可以试试:

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

因为它返回一个布尔值。

警告:常见的Ruby模式

定义的?方法就是答案。见上面接受的答案。

但是要小心……看看下面这个常见的红宝石图案:

 def method1
    @x ||= method2
 end

 def method2
    nil
 end

Method2总是返回nil。 第一次调用method1时,@x变量没有设置——因此method2将运行。而且 Method2将@x设为nil。

但是第二次调用method1时会发生什么呢?

记住@x已经被设置为nil。但是method2仍然会再次运行!!如果method2是一个昂贵的事业,这可能不是你想要的东西。

让定义?救援方法:

  def method1
    return @x if defined? @x
    @x = method2
  end

与大多数事情一样,关键在于实现细节。

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

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

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