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


当前回答

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

$ 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 -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"

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

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

使用定义的?关键字(文档)。它将返回一个包含项目类型的String,如果不存在则返回nil。

>> a = 1
 => 1
>> defined? a
 => "local-variable"
>> defined? b
 => nil
>> defined? nil
 => "nil"
>> defined? String
 => "constant"
>> defined? 1
 => "expression"

正如skalee评论的那样:“值得注意的是,设置为nil的变量是初始化的。”

>> n = nil  
>> defined? n
 => "local-variable"

你可以试试:

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

因为它返回一个布尔值。