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

Any Ruby variable is an object, so it can be uninitialized/unset (set to nil). nil? method returns true if it is not initialized:

b = nil
b.nil? # true
b = 'string value'
b.nil? # false

Arrays, strings, streams in Ruby can contain no data, so they can be empty. The empty? method returns true if so:

array = []
array.empty? # true
array << 5 << 4 # [5, 4]
array.empty? # false

string = "" # empty line
string.empty? # true

blank? is Active Support specific method (available in any object) and is available in Ruby On Rails with Active Support. It returns true if an object is nil or empty.


Feel it ;)

NIL?

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

EMPTY?

[].empty?
#=> true
nil.empty?
#=> undefined method
"".empty?
#=> true
" ".empty?
#=> false

BLANK?

[].blank?
#=> true
nil.blank?
#=> true
"".blank?
#=> true
" ".blank?
#=> true

In Ruby, nil in an object (a single instance of the class NilClass). This means that 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.

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.

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.

Because empty? is not defined for all objects you would get a NoMethodError if you called empty? on nil so to avoid having to write things like if x.nil? || x.empty? Rails adds the blank? method.


After answering, I found an earlier question, "How to understand nil vs. empty vs. blank in Rails (and Ruby)", so you should check the answers to that too.