Self or default if empty, DRY way

I really appreciate following idiom in Ruby: || "N/A"

It's DRY. No need for conditional structures, and repeating 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:[/.+/m] || "N/A"

Use to_s to support both nil and empty value with no cost in complexity:[/.+/m] || "N/A"
Published 2008-03-19 · Home 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() || "N\A" 140
Dejan Simic 2013-07-04 14:01:00 UTC

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