The Difference Between nil?, empty?, and blank? in Ruby
October 07, 2023
nil?
As expected, you can use nil? to check if an object is nil. It returns true only when the object is nil. For all other values, it returns false.
nil_object = nil
nil_object.nil? # true
data = Hash.new
data.nil? # falseempty?
You can use this method on strings, arrays, and hashes. It returns true in the following cases:
- String doesn’t have any characters, i.e.
str.length == 0 - Array doesn’t contain any elements, i.e.
arr.length == 0 - Hash doesn’t have any key-value pairs, i.e.
hash.length == 0
[].empty? # true
''.empty? # true
{}.empty? # true
nil.empty? # NoMethodError
false.empty? # NoMethodErrorIt’s important to note that an object can be empty and not nil. For example:
names = []
names.empty? # true
names.nil? # falseIf you try to call .empty? on a nil or any other object, Ruby throws NoMethodError.
nil.empty?
# undefined method `empty?' for nil:NilClass (NoMethodError)blank?
This is a nice syntactic sugar implemented in Rails. An object is blank if it’s nil, false, or empty. For example, nil,false, '', [], {}are all blank.
You can think of blank? as a shorthand for the following code.
!val || val.empty?Here's how it works for various values.
nil.blank? # true
false.blank? # true
''.blank? # true
[].blank? # true
{}.blank? # trueIn addition, .blank? returns true if a string contains only whitespace characters.
" ".blank? # trueRails also provides present?, which is the opposite of blank?. It checks if the value is not blank.