I find myself repeatedly looking for a clear definition of the differences of nil?
, blank?
, and empty?
in Ruby on Rails. Here\'s the
nil?
is a standard Ruby method that can be called on all objects and returns true
if the object is nil
:
b = nil
b.nil? # => true
empty?
is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true
if these objects contain no element:
a = []
a.empty? # => true
b = ["2","4"]
b.empty? # => false
empty?
cannot be called on nil
objects.
blank?
is a Rails method that can be called on nil
objects as well as empty objects.
nil?
is blank?
empty?
is blank?
empty?
is nil?
nil?
is empty?
tl;dr -- only use blank?
& present?
unless you want to distinguish between ""
and " "
I made this useful table with all the cases:
blank?
, present?
are provided by Rails.
Rails 4
an alternative to @corban-brook 's 'Array gotcha: blank?' for checking if an arrays only holds empty values and can be regarded as blank? true:
[ nil, '' ].all? &:blank? == true
one could also do:
[nil, '', "", " ",' '].reject(&:blank?).blank? == true
One difference is that .nil?
and .empty?
are methods that are provided by the programming language Ruby, whereas .blank?
is something added by the web development framework Rails.
Everybody else has explained well what is the difference.
I would like to add in Ruby On Rails, it is better to use obj.blank?
or obj.present?
instead of obj.nil?
or obj.empty?
.
obj.blank?
handles all types nil
, ''
, []
, {}
, and returns true
if values are not available and returns false
if values are available on any type of object.