Is it better to use obj.nil? or obj == nil and what are the benefits of both.
Personally, I prefer object.nil?
as it can be less confusing on longer lines; however, I also usually use object.blank?
if I'm working in Rails as that also checks to see if the variable is empty.
I find myself not using .nil?
at all when you can do:
unless obj
// do work
end
It's actually slower using .nil?
but not noticeably. .nil?
is just a method to check if that object is equal to nil, other than the visual appeal and very little performance it takes there is no difference.
Is it better to use obj.nil? or obj == nil
It is exactly the same.
and what are the benefits of both.
If you like micro optimizations all the objects will return false
to the .nil?
message except for the object nil
itself, while the object using the ==
message will perform a tiny micro comparison
with the other object to determine if it is the same object.