tags:

views:

272

answers:

4

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

+2  A: 

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.

Topher Fangio
A: 

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.

Garrett
problem with this approach as it matches `false` as well as `nil`.
banister
I wonder if "unless obj" is complete, or whether there should be something after it. With if obj.nil?, you know it's complete.
Andrew Grimm
Good point @banister!
Jay Godse
A: 

Some might suggest that using .nil? is slower than the simple comparison, which makes sense when you think about it.

But if scale and speed are not your concern, then .nil? is perhaps more readable.

ewall
+2  A: 

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.

OscarRyz
+1 - Good point about the micro comparison.
Topher Fangio