在Rails 3中调用id为nil

Sha*_*bov 5 ruby ruby-on-rails ruby-on-rails-3

在开发模式中:

nil.id
=> "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id"
Run Code Online (Sandbox Code Playgroud)

在生产模式中:

nil.id
=> 4
Run Code Online (Sandbox Code Playgroud)

为什么?

Ben*_*ret 11

在您的环境配置中查找说明以下内容的行:

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true # or false in production.rb
Run Code Online (Sandbox Code Playgroud)

这是为了防止您nil在开发模式下调用方法.我猜他们因生产中的性能原因而禁用它.

并且nil是ruby中的单个对象,这就是为什么id无论如何它都将是4.