- x is an Array.
- Notice the two comparisons below. The first should produce “true”, as expected. The second throws an error. What is going on here?
Why does negative comparison for nil not produce false in the second test?
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>'
I’d guess it’s because the value
x[2]['comments']['data'][1]is nil.You might want to use this helper method instead:
Use like this: