Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obj.nil? vs. obj == nil

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

like image 633
Danish Khan Avatar asked Dec 29 '09 00:12

Danish Khan


People also ask

Is it better to use OBJ nil or obj == nil?

The actual results showed that using obj as a nil check is the fastest in all cases. obj is consistently faster by 30% or more than checking obj. nil? . Surprisingly, obj performs about 3-4 times as fast as variations on obj == nil , for which there seems to be a punishing performance penalty.

Why does Ruby use nil?

Nil means nothing/nonexistent. Ask Matz. It's not different. Just a guess: Ruby is very lisp-like and nil is a value in lisp.

What does nil mean in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

Is nil the same as null Ruby?

nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.


2 Answers

Is it better to use obj.nil? or obj == nil

It is exactly the same. It has the exact same observable effects from the outside ( pfff ) *

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.

* See comments.

like image 137
OscarRyz Avatar answered Sep 19 '22 11:09

OscarRyz


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.

like image 30
Topher Fangio Avatar answered Sep 17 '22 11:09

Topher Fangio