Answer 1

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.

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.

Answer 2

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

Running .empty? on something that is nil will throw a NoMethodError.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

" ".blank? == true
" ".empty? == false

Rails also provides .present?, which returns the negation of .blank?.

Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:

[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true

NOTE: blank? and present? are Rails methods. They return NoMethodError in Ruby.

Source: http://stackoverflow.com/a/11029344/888278, http://stackoverflow.com/a/888877/888278