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 ob
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.
if object
tests if object
isn't either nil
or false
.
!object.nil?
tests if object
isn't nil
. (Rubydoc)
So when object
is false
, they have different values.
There is one and only one case in which !object.nil?
and object
evaluate to different results in a boolean context and that is if object
is false
. In all other situations the result is the same.
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 object
when protecting against object
being nil?):
No, you can always use if object
if you want to check against nil
.
Well. if object
will behave differently from if !object.nil?
if object=false
.
That's about it.
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.