11
Mar
08

Object-Oriented Approach to Blank Checking/Defaulting

Something I constantly find myself doing is checking to see if a value is blank, and returning something else if it is, otherwise the object itself:

birthday.blank? ? '0000-00-00' : birthday

I started thinking about how I could possibly eliminate the need for all these ternary operators, and came up with this:

class Object
  def or_if_blank(value)
    self.respond_to?(:blank) && self.blank? ? value : self
  end
end

Now we can do something like this:

birthday.or_if_blank('0000-00-00')

You could do something similar for nil, though a more general Ruby idiom is to just use the || operator, which does not work for blank.

On another note, if any of you are used to appending a “if object.respond_to?(:method)” predicate, check out this technique using try.


1 Response to “Object-Oriented Approach to Blank Checking/Defaulting”


  1. 1 oo blank checking — award tour Pingback on Apr 29th, 2008 at 10:02 pm

Leave a Reply




  • Ben Hughes

    I'm a freelance developer working with Ruby and other modern tools to build web applications, based currently out of Rochester, NY. I love to learn about new technologies and am always trying to achieve elegance and beauty through code.

    When I'm not writing software, I like to play tennis, dabble in jazz piano, and ponder economics. I'm a big fan of: world travel and cultures, jazz music, Korean food, coffee, and having interesting conversations.

  • Recommend Me
March 2008
M T W T F S S
« Feb   Apr »
 12
3456789
10111213141516
17181920212223
24252627282930
31