如何为NilClass重现未定义的方法错误

时间:2012-06-25 22:57:35

标签: ruby null

我想了解如何在Ruby 1.9中重现以下错误:

NoMethodError (undefined method `[]' for nil:NilClass):

这是我自己的兴趣。以下内容对我不起作用:

a = nil
a[:key]

它产生以下错误:

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.[]

1 个答案:

答案 0 :(得分:1)

您的代码在我的机器上运行(因为我无法格式化评论,所以提交答案):

⇨ irb
1.9.3p194 :001 > a = nil
 => nil 
1.9.3p194 :002 > a[:key]
  NoMethodError: undefined method `[]' for nil:NilClass
    from (irb):2
    from /Users/bjc/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'