Tuesday, March 4, 2008

Nil desperandum!

Which means literally, "Despair of Nothing!" Makes you wonder if Horace ever worked in software.

When is a null object reference not a null object reference? Why, when you can dereference it, of course.

If a Ruby method returns nil and I try to dereference it thinking I have a valid object reference, it's going to throw, right? Raise an exception? Hurl?

Erm, no. Actually, nil is an object. Let's have some fun with irb:

[chrisa@doppio ~]$ irb

Can I convert it to an integer?

irb(main):001:0> nil.to_i
=> 0

Yep. At least it's 0. How 'bout a string?

irb(main):002:0> nil.to_s
=> ""

Of course, it's an object, silly! And an array, etc.

irb(main):003:0> nil.to_a
=> []

This next one is really cool. Let's say you got this object reference back from ActiveRecord using MyModel.find(:first). Since you've dutifully followed the convention, you expect to get it's accession number by dereferencing the automagic property "id":

irb(main):004:0> nil.id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 4

Love that deprecation warning. We all hunt down and fix those right away, right? I spent a pleasant afternoon staring at the source of that one. Remember to read those web server logs carefully, kids!

No comments: