The Difference Between nil?, empty?, and blank? in Ruby
In Ruby, you can use nil? method to check if the object is nil. However, Ruby also provides empty? and there’s a blank? method in Rails. For a Ruby (or Rails) newbie, it can get quite confusing, it certainly did for me. This post explains which method to use when. Hope it simplifies things a little.
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? # false
empty?
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? # NoMethodError
It’s important to note that an object can be empty and not nil. For example:
names = []
names.empty? # true
names.nil? # false
If 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? # true
In addition, .blank? returns true if a string contains only whitespace characters.
" ".blank? # true
Rails also provides present?, which is the opposite of blank?. It checks if the value is not blank.
Sign up for my newsletter
Let's learn to become better developers.