Thursday, July 29, 2010

nib Method to Return nil if blank? in Ruby

There are a number of solutions out there for returning nil if a variable is nil or blank? in Ruby but I came up with this which I think is easiest. Throw it into some .rb file under lib in your Rails project or just add it to a script.

class Object
  
  # Return nil if object.self.blank?, otherwise return object.self
  #
  # Author::  Gary S. Weaver
  
  def nib
    self.blank? ? nil : self
  end

end

Example usage:

>> 'John Doe'.nib
=> "John Doe"
>> ' '.nib
=> nil
>> ''.nib
=> nil
>> nil.nib
=> nil
>> 0.nib
=> 0
This allows you to do the following: (for example, in a view)
@director_name.nib || 'no name specified'
Note: nib stands for "nil if blank?".

No comments: