Self or default if empty, DRY way

I really appreciate following idiom in Ruby:

          person.phone || "N/A" 
          

It’s DRY. No need for conditional structures, and repeating person.phone in condition and as return value.

But lets say you don’t control your data source, and there is an empty string instead of nil when data is not available (sounds familiar?). How would you deal with that and keep things simple and DRY?

Well, basicly all you need is a String method that will return nil if string is empty, or self if it’s not empty. String object doesn’t have that kind of method, at least not that specialized. Regexp to rescue. Lets try this:

          >> ""[/.+/m]
          => nil
          
          >> "ruby"[/.+/m]
          => "ruby" 
          

Nice. So solution for the problem above is:

          person.phone[/.+/m] || "N/A" 
          

Throw andand in game to support both nil and empty value with no cost in complexity:

          person.phone.andand[/.+/m] || "N/A" 
          

« Home | This article was published on March 19, 2008.

Comments

Any thoughts?