What if it's nil? What if it's method is nil?
written by Steven on March 12, 2008
Chris Wanstrath wrote a nice little post about a method he created called try(), I thought this was pretty cool, but I really want to be able to specify the return value if the object is nil. Plus, what if I want to use this sweetness on a method? So I wrote two methods to do just that:
class Object
def if_nil out = nil
return out if nil?
self
end
def if_method_nil method, out = nil
return out if nil?
return send(method) if out.nil?
return out if respond_to?(method) && send(method).nil?
send method
end
end
And here are some tests for them, which illustrate their usage:
def test_if_nil1
n = nil
assert_equal nil, n.if_nil
end
def test_if_nil2
n = 1
assert_equal 1, n.if_nil
end
def test_if_nil3
n = :yo
assert_equal :yo, n.if_nil
end
def test_if_nil4
n = nil
assert_equal 'blah', n.if_nil('blah')
end
def test_if_method_nil1
n = nil
assert_equal nil, n.if_method_nil(:to_s)
end
def test_if_method_nil2
n = 1
assert_raise NoMethodError do
n.if_method_nil :yo
end
end
def test_if_method_nil3
n = 1
assert_nothing_raised do
assert_equal '1', n.if_method_nil( :to_s)
end
end
def test_if_method_nil4
n = 1
assert_nothing_raised do
assert_equal '1', n.if_method_nil( :to_s, 'blah')
end
end
def test_if_method_nil5
n = nil
assert_nothing_raised do
assert_equal 'blah', n.if_method_nil( :to_s, 'blah')
end
end
Learn how LessEverything built their consultancy to over $1,000,000 annual revenue at LessMoney Conference, June 7th in Tampa Florida. Each attendee will get early access to our upcoming ebook as well.
Leave a Comment
About Steven
Popular Articles
Subscribe

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.

2 Comments
Y’know, Real Programming Languages don’t have this problem. In Ocaml (for instance), you never get a NullPointerException analog, because the type system knows when it can be null/nil, and the coder has to explicitly handle the case.
And if you don’t want nil, you just don’t handle the case. Then the compiler won’t let you pass nil in. :)
Wow, I always heard ocaml was cool, now it sounds kinda like C#/Java (which is to say sucky).
This is simply a nice one liner way to handle nil checking. It’s not about passing in params to a method. Instead of doing:
val = blah.nil? ? ‘value’ : blah
you can do
val = blah.if_nil ‘value’
It’s just a bit of syntactic sugar.