Ruby - 如果变量不存在,我该如何处理它?

jun*_*nky 4 ruby

我想要做 puts blob

但如果blob变量不存在,我得到

NameError: undefined local variable or method `blob' for main:Object
Run Code Online (Sandbox Code Playgroud)

我试过了

blob?  
blob.is_a?('String')
puts "g" if blob  
puts "g" catch NameError
puts "g" catch 'NameError'
Run Code Online (Sandbox Code Playgroud)

但没有工作.

我可以通过使用@instance变量来绕过它,但这就像我应该知道的那样作弊并且相应地处理没有价值的问题.

alf*_*alf 13

在这种情况下,你应该这样做:

puts blob if defined?(blob)
Run Code Online (Sandbox Code Playgroud)

或者,如果你想检查nil:

puts blob if defined?(blob) && blob
Run Code Online (Sandbox Code Playgroud)

defined?如果定义了参数的类型,则该方法返回表示参数类型的字符串nil.例如:

defined?(a)
=> nil
a = "some text"
=> "some text"
defined?(a)
=> "local-variable"
Run Code Online (Sandbox Code Playgroud)

使用它的典型方法是使用条件表达式:

puts "something" if defined?(some_var)
Run Code Online (Sandbox Code Playgroud)

更多defined?关于这个问题.