What is the difference between .nil?, .empty? and .blank?

.nil?

.nil? can be used on any object. It determines if the object has any value or not, including 'blank' values.

For example:

example = nil
example.nil?  # true

"".nil?  # false

Basically .nil? will only ever return true if the object is in fact equal to 'nil'

.empty?

.empty? is only called on objects that are considered a collection. This includes things like strings (a collection of characters), hashes (a collection of key/value pairs) and arrays (a collection of arbitrary objects). .empty? returns true is there are no items in the collection.

For example:

"".empty? # true
"hi".empty?   # false
{}.empty?  # true
{"" => ""}.empty?   # false
[].empty?   # true
[nil].empty?  # false

nil.empty?  # NoMethodError: undefined method `empty?' for nil:NilClass

Notice that .empty? can't be called on nil objects as nil objects are not a collection and it will raise an exception.

Also notice that even if the items in a collection are blank, it does not mean a collection is empty.

.blank?

.blank? is basically a combination of .nil? and .empty? It's useful for checking objects that you assume are collections, but could also be nil

For example:

"".blank? # true
"hi".blank?   # false
{}.blank?  # true
{"" => ""}.blank?   # false
[].blank?   # true
[nil].blank?  # false

nil.blank?  # true