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
If you wanted it to build a product you’d find a way to get time to work on it. If you really wanted to start that new hobby you’d sacrifice something to find the time and money to do it.
I'll define a "Wannabe Entrepreneur" as someone who has never made money from their businesses. Here are the different types of wannabes.
In the past few years I've built go-carts, built a 200+ sq ft workshop, written several eBooks. How do I create a life where I have time to work on side projects?
Receive 5 Software projects mistakes we have made over the years and how to avoid them.