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"

Use to_s to support both nil and empty value with no cost in complexity:

person.phone.to_s[/.+/m] || "N/A"
Published 2008-03-19 00:00:00 +0100 · Home
Assets.github.com%2fimages%2fgravatars%2fgravatar user 420
Ryan Hall 2013-05-02 23:23:27 UTC

If you are using Rails or just ActiveSupport, you can use the method .presence()

person.phone.presence || "N\A"

http://api.rubyonrails.org/classes/Object.html#method-i-presence

Assets.github.com%2fimages%2fgravatars%2fgravatar 140
Dejan Simic 2013-07-04 14:01:00 UTC

Right. Note that this article was before ActiveSupport introduced presence.