When to use .nil? in Ruby methods
The problem
Nil? is overused. I find myself deleting it a lot.
I stopped using nil? once I learned that:
1 2 3 4 5 |
if person.nil? make_person end |
Has the same effect as
1 2 3 4 5 |
unless person make_person end |
or
1 |
make_person unless person
|
Thus, when I read code, it is equally clear to me what someone means when they use either one.
Given that, it strikes me as bulky whenever I see nil?, unless of course the person legitimately needs a bool, which is rare.
Another reason
Calling nil? also makes your code slower.
Contrived example
This is obviously a pretty contrived example, but check it out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
require 'benchmark' Benchmark.bm do|b| b.report("without .nil?") do cat = nil bat = 'vampire' 2_000_000.times do unless bat true if cat end end end b.report("with nil? ") do cat = nil bat = 'vampire' 2_000_000.times do unless bat.nil? true unless cat.nil? end end end end |
Results user system total
without .nil? 0.290000 0.000000 0.290000 ( 0.298643)
with nil? 0.780000 0.000000 0.780000 ( 0.788894)
So, without nil? is, at least in this not at all scientific test, more than twice as slow. In Ruby, we tend to not care about speed, by why gimp yourself on purpose? Especially when the faster way is equally, if not more, clear?
When to use nil? in Ruby methods? Imo never.
May 21, 2009
