Translate

August 24, 2011

Difference between .nil?, .empty?, .blank?, .present?

I have been puzzled or confused with the method  nil?, empty?, blank? And present?
How do you do it differently?

nil? -> This can be used with any object will return true (true) when the object is not nil and false (false) if the object has something in it.

Example:.
nil. nil?
 # => true.
 [].nil?
 # => false.
 "".nil?
 # => false.
 "  ".nil?
 # => false.

empty? -> This can not be used with any object, this is valid for using with object of class array, Hashes and String. This will return true (true) if the object does not have any value at all.

    When empty? is used for nil object it will throw an error "NoMethodError".

When used with strings, arrays and hashes
    String length == 0.
    Array length == 0.
    Hash length == 0.

Example:.
[].empty?
 # => true.
 nil.empty?
 # => Undefined method.
 "".empty?
 # => true.
 "  ".empty?
 # => false
empty?
 # => false.

blank? ->
This can be used for any object and This will returns true if the object has a value of nil, false, empty, or a white space string.

Example:.
[]. blank?
 # => true.
 nil.blank?
 # => true.
 "".blank?
 # => true.
 "    ".blank?
 # => true.
 false.blank?
 # => true

present? -> This can be used with any object will be restored when the object has a value that is not nil, false, empty, or a white space string. This behave exact opposite of blank?

    blank? ! = present?

Example:.
[].present?
 # => false.
 nil.present?
 # => false.
 "".present?
 # => false.
 "  ".present?
 # => false.
 false.present?
 # => false.
Summary:

    nil? When the value is nil for each object.
    empty? To check for the empty string, array, hash.
    blank? To check the object has a value of nil
    present? The opposite of blank?

Finally, With different conditions you can choose best suited methods.
Note: .blank? and .present? are rails methods.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

Post a Comment