Ruby:“如果 !object.nil?"或“如果对象" [英] Ruby: "if !object.nil?" or "if object"

查看:40
本文介绍了Ruby:“如果 !object.nil?"或“如果对象"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它们在 if/else/end 语句中使用时是否相同?你平时做些什么?我想知道 object!object.nil? 是否有任何细微的差异或边缘情况会有所不同.

Are they the same when used in an if/else/end statement? What do you usually do? I'm wondering if there are any subtle differences or edge cases where object and !object.nil? would respond differently.

推荐答案

存在差异.例如:

false.nil?
# => false

所以:

if !false.nil?
  'foo'
end
# => "foo"

if false
  'foo'
end
# => nil

正如@tokland 所建议的,在大多数情况下,使用 !obj.nil? 构造是不必要的.

As @tokland suggested, in most cases using !obj.nil? construction is unnecessary.

这篇关于Ruby:“如果 !object.nil?"或“如果对象"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆