Allan & Steve are the chubby founders of LessEverything. This is their blog, hear them rant, praise, give advice and talk about Just Stuff, Less Accounting, Lovd by Less, More Honey, Less Memories, Code, Business, Design, Marketing
March 12th, 2008

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

written by Steven Bristol

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

2 Responses to “What if it's nil? What if it's method is nil? ”

  1. Robert Fischer March 12th, 2008

    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. :)

  2. Steven Bristol March 12th, 2008

    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.

Leave a Reply