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

About this user

Rails Garden http://www.railsgarden.com/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Default Values for Blank Values OO-style

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")
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS