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


当前回答

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

其他回答

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

当变量不存在时:

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

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

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

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

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

希望这能有所帮助!:)

这里有一些代码,没有火箭科学,但它工作得足够好

require 'rubygems'
require 'rainbow'
if defined?(var).nil?  # .nil? is optional but might make for clearer intent.
 print "var is not defined\n".color(:red)
else
 print "car is defined\n".color(:green)
end

显然,着色代码是不必要的,在这个玩具示例中只是一个漂亮的可视化。