obj.nil? vs. obj == nil

前端 未结 7 877
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 22:08

Is it better to use obj.nil? or obj == nil and what are the benefits of both?

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 22:44

    In many cases, neither, just test the boolean truth value

    Although the two operations are very different I'm pretty sure they will always produce the same result, at least until someone out on the edge of something decides to override Object's #nil? method. (One calls the #nil? method inherited from Object or overridden in NilClass and one compares against the nil singleton.)

    I would suggest that when in doubt you go a third way, actually, and just test the truth value of an expression.

    So, if x and not if x == nil or if x.nil?, in order to have this test DTRT when the expression value is false. Working this way may also help to avoiding tempting someone to define FalseClass#nil? as true.

提交回复
热议问题