Ruby 101: The Mysterious Dr. Nil
Photo credit: http://www.flickr.com/photos/biczzz/365774667/
UPDATE: Thanks goes to Dan for pointing out my Java mistake.
Zilch, nada, nothing
Many programming languages have a keyword to mean that a variable holds “no value.”
- When I first learned C, I thought
NULLwas a keyword at first; later I learned it was justdefine‘d to be 0 - C# has the
nullkeyword - Java has
null - VB uses the keyword
Nothing - SQL uses
NULL.
Ruby also has a way to represent the same concept with the keyword nil:
my_var = nil
In Ruby, there are several ways to find out of a variable has the nil value. First, there’s the obvious:
if my_var == nil
puts "It's nil!"
end
This is most similar to how you would check in other languages. But there is another way, too.
if my_var.nil?
puts "It's nil!"
end
If you’re new to Ruby, the above if statement should make your head turn just a bit. If my_var is nil, how can we call a method on it? In C#, calling a method on a null reference would throw an exception. Yet, here we are, calling a method on an object that’s nil.
Get Out The Magnifying Glass
Let’s look more closely at the nil? method. It’s available on every Ruby object. Open up an irb session:
1.nil?
=> false
"hello".nil?
=> false
my_var.nil?
=> true
So everything can test itself to find out if it’s nil. To understand how we can call a method like nil? on an object that itself is nil, let’s be more precise: we’re sending the message “nil?” to the my_var object. In order for this to work, my_var must refer to an actual object taking up actual memory. In C#, doing something like my_var = null makes my_var point to nowhere. It will not refer to any object at all. But in Ruby, when we say:
my_var = nil
we are definitely not saying that my_var does not refer to anything. In fact, my_var still refers to a valid object at a valid memory location! What’s more, it’s an object that can respond to messages, including the “nil?” message. Strange, right?
Well, if my_var really is a real reference to a real object, exactly what object is it referring to?
It’s Just Another Object
It turns out that the nil keyword in Ruby evaluates to a predefined global object. (I can’t bring myself to say “global variables” because global variables are evil, right?) You know how in Ruby, we like to say that everything is an object? nil is no exception! Behold:
nil.class
=> NilClass
nil.object_id
=> 4
Awesome! We’ve proven that nil is a real object, having a class and object_id just like any other object. There’s really no magic at all behind the statement:
my_var = nil
Now we can see, all we’re doing is assigning my_var to refer to the one and only nil object. It’s exactly no different from any other assignment statement in Ruby: your variable just happens to refer to the global object nil, no more and no less.
However, the language does give special treatment to the nil object in certain sitations, like if statements. if knows to evaluate to false if the given expression refers to nil:
if my_var
puts "It's not nil!"
end
Here, the puts statement will not execute if my_var is false, or if my_var refers to the global nil object. This special treatment is necessary, because normally any non-nil object reference will evaluate to true:
my_var = Array.new
if my_var
puts "It's not nil!"
end
This time, the puts will execute and display the string It’s not nil!. In Ruby, anything that’s not false and is not nil evaluates to true. Since my_var refers to an Array object, it is not false nor does it refer to nil, and so the condition evaluates to true.
That’s a brief look at the mysterious nil in Ruby. Questions or comments? Drop me a comment below.



Java actually has a null keyword, not nil.
With extension methods (C# 3.0+), you can simulate calling a method on a reference pointing to null.
static bool IsNil(this object o) { return o == null; }
Usage:
var s = "hello"; Console.WriteLine(s.IsNil()); // false s = null; Console.WriteLine(s.IsNil()); // true
@Dan: Thanks for spotting that! I've updated the text.
@Derek: Thanks for the example. To me, it's more proof that C# 3.0+ is being influenced heavily by dynamic languages like Ruby.
"Here, the puts statement will not execute if myvar is false, or if myvar refers to the global nil object."
heh, i thought you were gonna drop into a recursive discussion about FalseClass at this point, but you successfully avoided the wormhole. :]
"If you’re new to Ruby, the above if statement should make your head turn just a bit" ... unless you've been programming Smalltalk within the last 30 years.
Sorry, just another Smalltalker moaning as usual...
In Java referencing a null object will result in the famous NullPointerException. Nothing you can do. In Ruby you get a NoMethodError on NilClass. And ruby wasn't ruby if nothing could be done ...
class NilClass def method_missing(sym, *args) nil end end
:-)
Hi!
May I say that if you open up an irb session and type my_var.nil?
you don't get true but a NameError?
What you could do is
my_var=whatever if false => nil my_var.nil? => true
though!
Hi everyone. Great site. Hold on.: cheap phentermine[/url] [url=http://www.certmag.com/forums/member.php?u=6229&key=Buy_Lipitor_Online]buy lipitor online[/url] [url=http://www.kypros.org/LearnGreek/user/view.php?id=189258&key=Levaquin-Cheapest]purchase Levaquin[/url] [url=http://www.kypros.org/LearnGreek/user/view.php?id=189411&key=Ambien-Cheapest]buy discount ambien[/url] [url=http://learn.trimurti.net/user/view.php?id=1790&key=Lexapro-Cheapest]Lexapro cheapest[/url] [url=http://www.kypros.org/LearnGreek/user/view.php?id=189403&key=Stromectol-Cheapest]Stromectol discount[/url] [url=http://www.learning-objects.net/training/user/view.php?id=13&key=Lotrisone-Cheapest]Lotrisone canada[/url] [url=http://www.learnernet.org/moodle/user/view.php?id=546&key=Celebrex-Cheapest]order Celebrex cheap/urlorder cheap lipitor[/url] [url=http://community.enemyterritory.com/forums/member.php?u=54655&key=Buy-Fioricet-Cheap]buy fioricet online[/url] buy lipitor online purchase Levaquin order cheap lipitor buy fioricet online Lotrisone canada Stromectol discount buy cheap phentermine order Celebrex cheap buy discount ambien Lexapro cheapest http://www.kypros.org/LearnGreek/user/view.php?id=189411&key=Ambien-Cheapest http://www.learning-objects.net/training/user/view.php?id=13&key=Lotrisone-Cheapest http://www.learnernet.org/moodle/user/view.php?id=546&key=Celebrex-Cheapest http://www.learnernet.org/moodle/user/view.php?id=545&key=Lexapro-Cheapest http://www.kypros.org/LearnGreek/user/view.php?id=189258&key=Levaquin-Cheapest http://community.enemyterritory.com/forums/member.php?u=54658&key=Buy-Phentermine-Cheap http://community.enemyterritory.com/forums/member.php?u=54655&key=Buy-Fioricet-Cheap http://www.certmag.com/forums/member.php?u=6229&key=Buy_Lipitor_Online http://learn.trimurti.net/user/view.php?id=1790&key=Lexapro-Cheapest http://www.kypros.org/LearnGreek/user/view.php?id=189403&key=Stromectol-Cheapest
Greetings Very good web site. I loved it. Found invaluable information. Just what I was looking for :-) Regards and best wishes: personal loan[/url] [url=http://web.bgu.edu/moodle/user/view.php?id=342&key=Ringtones-download]verizon ringtone/urlUnsecured personal loans[/url] [url=http://www.logicalgamers.com/member.php?u=20857&key=Replica-Rolex-Watches]Replica Rolex Watches[/url] [url=http://community.enemyterritory.com/forums/member.php?u=55661&key=Replica_Rolex_Watches]Replica Rolex Watches[/url] [url=http://www.logicalgamers.com/member.php?u=20600&key=Download_Ringtones_Online]Free Download Ringtones[/url] [url=http://discussion.treocentral.com/member.php?u=129385&key=Download-Ringtones-Online]free ringtone[/url] [url=http://ecampus.learningstreet.org/user/view.php?id=5206&key=Replica-Handbags-Online]replica handbag[/url] [url=http://courses.legalaideducation.org/user/view.php?id=802&key=Ringtones-download-online]free nokia ringtone[/url] [url=http://moodle.cerrocoso.edu/user/view.php?id=11257&key=Personal-Loans-Online]bad credit personal loan[/url] verizon ringtone Unsecured personal loans Free Download Ringtones Replica Rolex Watches free ringtone bad credit personal loan replica handbag fast personal loan free nokia ringtone Replica Rolex Watches http://www.logicalgamers.com/member.php?u=20600&key=Download_Ringtones_Online http://courses.legalaideducation.org/user/view.php?id=802&key=Ringtones-download-online http://moodle.cerrocoso.edu/user/view.php?id=11257&key=Personal-Loans-Online http://community.enemyterritory.com/forums/member.php?u=55661&key=Replica_Rolex_Watches http://discussion.treocentral.com/member.php?u=129385&key=Download-Ringtones-Online http://www.learning-objects.net/training/user/view.php?id=14&key=personal-loans-online http://ecampus.learningstreet.org/user/view.php?id=5206&key=Replica-Handbags-Online http://discussion.treocentral.com/member.php?u=129457&key=Personal_Loans_Online http://web.bgu.edu/moodle/user/view.php?id=342&key=Ringtones-download http://www.logicalgamers.com/member.php?u=20857&key=Replica-Rolex-Watches