Is it better to use obj.nil?
or obj == nil
and what are the benefits of both?
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.