Default Values For Blank Values OO-style
Join the DZone community and get the full member experience.Join For Free
In Ruby the idiom || can be used to provide a default value if something is nil. This can't be done with blank since an empty string is not nil and will short-circuit the || operator, leaving most of us to to do something like "name.blank? ? 'John Doe' : name". Here's a way to do this OO-style:
class Object def or_if_blank(value) self.respond_to?(:blank) && self.blank? ? value : self end end name.or_if_blank("John Doe")
Opinions expressed by DZone contributors are their own.