nil的ruby测试会抛出错误

时间:2011-02-26 08:14:20

标签: ruby comparison null

  1. x是一个数组。
  2. 请注意下面的两个比较。正如预期的那样,第一个应该产生“真实”。第二个抛出错误。这是怎么回事?
  3. 为什么nil的负面比较在第二次测试中不会产生错误?

    ruby-1.9.2-p136 :079 > x[2]['comments']['data'][0]['from']['name'] != nil
     => true 
    
    x[2]['comments']['data'][1]['from']['name'] != nil
    NoMethodError: You have a nil object when you didn't expect it!
    You might have expected an instance of Array.
    The error occurred while evaluating nil.[]
        from (irb):78
        from /Users/justinz/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/commands/console.rb:44:in `start'
        from /Users/justinz/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/commands/console.rb:8:in `start'
        from /Users/justinz/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.3/lib/rails/commands.rb:23:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
    

4 个答案:

答案 0 :(得分:2)

我猜是因为值x[2]['comments']['data'][1]是零。

您可能希望使用此辅助方法:

def nullsafe_index(a, keys)
    keys.each{|key|
        return nil if a.nil?
        a = a[key]
    }
    return a
end

像这样使用:

nullsafe_index(x, [2, 'comments', 'data', 0, 'from', 'name']).nil?

答案 1 :(得分:1)

x [2] ['comments'] ['data'] [1]是一个空哈希,所以当你在它上面调用['from']时,结果是nil,这意味着调用['name']在nil的结果上,产生错误。以下是如何重现它:

x = {}
x['from'] #=> nil
x['from']['name'] #=> NoMethodError

您可以将您的请求视为函数调用的集合:

x[2]['comments']['data'][1]['from']['name']
# is equivalent to:
x.[](2).[]('comments').[]('data').[](1).[]('from').[]('name')

如果这些函数调用中的任何一个返回nil,则不能在没有错误的情况下对其进行另一个[]函数调用。

答案 2 :(得分:0)

看起来x[2]['comments']['data']没有第二个元素。这相当于调用nil['from'],这也会引发异常。

答案 3 :(得分:0)

x[2]['comments']['data'][1] == nil

尝试评估表达的每一部分:

x[2]
x[2]['comments']
x[2]['comments']['data']
x[2]['comments']['data'][1]
x[2]['comments']['data'][1]['from']
x[2]['comments']['data'][1]['from']['name']