nil? vs empty? vs blank? in ruby

less than 1 minute read

nil?

This method is available on all objects and returns true only when the object is nil.

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

empty?

This method is available on String, Array and Hash and returns true only when they are empty. Empty here means the object is not nil but does not have any value inside.

For example:

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

blank?

ℹ️ #blank? is a rails method

An object is blank if it’s false, empty, or a whitespace string.

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

Comparison

#nil? #empty? #blank?
nil true NoMethodError true
[] false true true
{} false true true
"" false true true
" " false false true
1 false NoMethodError false
true false NoMethodError false
false false NoMethodError true

Tags:

Categories:

Updated: