Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Default Values for Blank Values OO-style (See related posts)

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")

You need to create an account or log in to post comments to this site.


Click here to browse all 4839 code snippets

Related Posts