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

时间:2012-06-20 14:23:16

标签: ruby

我想做puts blob

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

NameError: undefined local variable or method `blob' for main:Object

我试过

blob?  
blob.is_a?('String')
puts "g" if blob  
puts "g" catch NameError
puts "g" catch 'NameError'

但没有工作。

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

2 个答案:

答案 0 :(得分:13)

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

puts blob if defined?(blob)

或者,如果你想检查nil:

puts blob if defined?(blob) && blob

defined?方法返回表示参数类型的字符串(如果已定义),否则返回nil。例如:

defined?(a)
=> nil
a = "some text"
=> "some text"
defined?(a)
=> "local-variable"

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

puts "something" if defined?(some_var)

有关this questiondefined?的更多信息。

答案 1 :(得分:0)

class Object
  def try(*args, &block)
    if args.empty? and block_given?
      begin
        instance_eval &block
      rescue NameError => e
        puts e.message + ' ' + e.backtrace.first
      end
    elsif respond_to?(args.first)
      send(*args, &block)
    end
  end
end

blob = "this is blob"
try { puts blob }
#=> "this is blob"
try { puts something_else } # prints the service message, doesn't raise an error
#=> NameError: undefined local variable or method `something_else' for main:Object
相关问题