What if it's nil? What if it's method is nil?

Written by on Mar 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 ifmethodnil 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 testifnil1 n = nil assertequal nil, n.ifnil end

def testifnil2 n = 1 assertequal 1, n.ifnil end

def testifnil3 n = :yo assertequal :yo, n.ifnil end

def testifnil4 n = nil assertequal ‘blah’, n.ifnil(‘blah’) end

def testifmethodnil1 n = nil assertequal nil, n.ifmethodnil(:to_s) end

def testifmethodnil2 n = 1 assertraise NoMethodError do n.ifmethodnil :yo end end

def testifmethodnil3 n = 1 assertnothingraised do assertequal ‘1’, n.ifmethodnil( :to_s) end end

def testifmethodnil4 n = 1 assertnothingraised do assertequal ‘1’, n.ifmethodnil( :to_s, ‘blah’) end end

def testifmethodnil5 n = nil assertnothingraised do assertequal ‘blah’, n.ifmethodnil( :to_s, ‘blah’) end end

 

Meet
Steven

Hi I'm Steven,

I wrote the article you're reading... I lead the developers, write music, used to race motorcycles, and help clients find the right features to build on their product.

Get Blog Updates