Computer Science Canada

if_not_ni

Author:  wtd [ Fri Nov 23, 2007 2:35 pm ]
Post subject:  if_not_ni

code:
class ElseHandler
    def otherwise(&blk)
        blk.call
    end
end

class Object
    def otherwise(&blk)
        self
    end

    def if_not_nil(&blk)
        if self.is_a? NilClass
            ElseHandler.new
        elsif blk
            yield self
        end
    end
end


And now...

code:
doSomethingThatReturnsNil.if_not_nil { |v| v.doSomething }.otherwise { doSomethingElse }


Can replace:

code:
tmp = doSomethingThatReturnsNil

if tmp
    tmp.doSomething
else
   doSomethingElse
end


: