如何检查一个变量是否在Ruby中定义?是否有isset类型的方法可用?
当前回答
此外,你可以检查它是否通过插值在字符串中定义,如果你编码:
puts "Is array1 defined and what type is it? #{defined?(@array1)}"
如果定义了类型,系统会告诉您。 如果没有定义,它将返回一个警告,说变量没有初始化。
希望这能有所帮助!:)
其他回答
定义?(your_var)将工作。取决于你在做什么你也可以做your_var。nil?
使用定义的?YourVariable 保持简单,傻瓜..;)
应该提到的是,使用defined来检查一个特定的字段是否在哈希中设置,可能会产生意想不到的行为:
var = {}
if defined? var['unknown']
puts 'this is unexpected'
end
# will output "this is unexpected"
这里的语法是正确的,但定义?Var ['unknown']将被求值为字符串"method",因此if块将被执行
检查哈希中是否存在键的正确符号是:
if var.key?('unknown')
试着用“除非”而不是“如果”
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
留下一个非常简单的例子,以防有用。
当变量不存在时:
if defined? a then "hi" end
# => nil
当变量存在时:
a = 2
if defined? a then "hi" end
# => "hi"