Ruby:“如果 !object.nil?” 或“如果对象”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18060790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: "if !object.nil?" or "if object"
提问by bigpotato
Are they the same when used in an if/else/endstatement? What do you usually do? I'm wondering if there are any subtle differences or edge cases where objectand !object.nil?would respond differently.
它们在if/else/end语句中使用时是否相同?你平常都做什么?我想知道是否有任何细微的差异或边缘情况,object并且!object.nil?会做出不同的反应。
回答by Marek Lipka
There are differences. For example:
存在差异。例如:
false.nil?
# => false
So:
所以:
if !false.nil?
'foo'
end
# => "foo"
if false
'foo'
end
# => nil
As @tokland suggested, in most cases using !obj.nil?construction is unnecessary.
正如@tokland 所建议的,在大多数情况下使用!obj.nil?构造是不必要的。
回答by Christopher Oezbek
There is one and only one case in which !object.nil?and objectevaluate to different results in a boolean context and that is if objectis false. In all other situations the result is the same.
有一种且只有一种情况,其中!object.nil?andobject在布尔上下文中评估为不同的结果,即 if objectis false。在所有其他情况下,结果都是一样的。
With this, I think we can answer your real question (which is: Is there any situation where I must use if !object.nil?instead of just if objectwhen protecting against objectbeing nil?):
有了这个,我想我们可以回答你真正的问题(即:有什么情况我必须使用if !object.nil?而不是仅仅if object在防止object为零时使用?):
No, you can always use if objectif you want to check against nil.
不,if object如果你想检查,你可以随时使用nil。
回答by Yu Hao
回答by Anton
Well. if objectwill behave differently from if !object.nil?if object=false.
好。if object将与if !object.nil?if不同object=false。
That's about it.
就是这样。
回答by Logan Serman
Objects can override nil?but they cannot be falsely unless they are nil or false. Personally I use nil?or ActiveSupport's present?so that I maintain that flexibility. I also think it reads a bit better.
对象可以覆盖,nil?但它们不能是错误的,除非它们是 nil 或 false。我个人使用nil?ActiveSupport 或 ActiveSupport,present?以便保持这种灵活性。我也觉得读起来好一点。

