Monday 25 March 2013

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

1) nil

In Ruby, nil in an object (a single instance of the class NilClass) so methods can be called on it. nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else.


2) empty

 empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true if the object contains no elements.


3) blank

blank? is not a standard Ruby method but is added to all objects by Rails and returns true for nil, false, empty, or a whitespace string.


Examples :



nil.nil?
=> true

false.nil?
=> false

1.nil?
=> false

0.nil?
=> false

"".nil?
=> false

[].nil?
=> false

"".empty?
=> true

"abc".empty?
=> false

[].empty?
=> true

[1, 2, 3].empty?
=> false

1.empty?
=> NoMethodError

nil.blank?
=> true

[].blank?
=> true

['a'].blank?
=> false








No comments:

Post a Comment