We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Devyani • 8 years ago

Great Article. Very useful

Darek • 9 years ago

Good article. Thank You for explanation on nil value. Good to know it is an singleton.

Sandyartha • 9 years ago

huhu Thanks Brother, helpful

Rubyist-

JIMz • 9 years ago

thanks for the insight !! these do help ~

ibgib • 9 years ago

2016 and your article is still helping people...thanks!

kelly • 10 years ago

So.... 1.object_id = 3
and 2.object_id = 5
3.object_id = 7

Bring my shotgun im gonna shoot this logic.

Charles • 10 years ago

Very well explained. I am wondering if Ruby has got the similar way where null is handled with Optional in Scala and Java 8

Nish • 10 years ago

Very helpful - thanks!

Jess • 11 years ago

This ruby n00b found this article helpful. Thank you.

Taldar • 12 years ago

Hey, great article. Thanks for mentioning how `Fixnum` ids are just the left-shift-plus-one of the value they represent. That's super cool. It raises an important question for a Ruby learner like myself: are `Fixnum`s actual objects, or are they just pseudo-objects?

Doug • 13 years ago

This was really helpful. Thanks for taking the time to explain.

poffuomo • 13 years ago

Well done, your articles are really clear and useful!

Joris • 13 years ago

Hey,

Learning Ruby right now, your article helped me out.
Thanks!

Matt • 13 years ago

No, this does not work.

Calling:
if my_object.nil?

If my_object is null results in an error.

Łukasz Wróbel • 13 years ago

> No, this does not work.

> Calling:
> if my_object.nil?

> If my_object is null results in an error.

It does work, but only for objects being **potentially** nil. That is, a reference has to exist.

Calling `nil?` on an existing variable will always work, though calling this (or any other) method on an undefined variable causes the `NameError` to be raised.

To achieve what you wanted to achieve, you can call `defined?`:

> defined? my_object
=> nil

> my_object = 1
> defined? my_object
=> "local-variable"

> my_object = nil
> defined? my_object
=> "local-variable"
> my_object.nil?
=> true

Rob • 14 years ago

Really clear and thorough explanation, thanks.

So you're saying that I should always write:
`if x.object_id == 4`
when I want to see if x is nil, then?

Just kidding.

Ray • 15 years ago

Why didn't you use the "unless" version?

Łukasz Wróbel • 15 years ago

Just for the sake of readability; I think that "if my_object.nil?" is much more clearer in this case. I usually use the "unless" keyword in this way:

raise NotFound unless @post

Milan Dobrota • 15 years ago

Should be:

unless my_object.nil?
my_object.display_info()
else
puts "There is no object!"
end

Łukasz Wróbel • 15 years ago

Of course there was a mistake... I've already fixed it, many thanks!