I find myself repeatedly looking for a clear definition of the differences of nil?
, blank?
, and empty?
in Ruby on Rails. Here's the closest I've come:
blank?
objects are false, empty, or a whitespace string. For example,""
," "
,nil
,[]
, and{}
are blank.nil?
objects are instances of NilClass.empty?
objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.
Is there anything missing, or a tighter comparison that can be made?
Quick tip:
!obj.blank? == obj.present?
Can be handy/easier on the eyes in some expressions
Don't forget
any?
which is generally!empty?
. In Rails I typically check for the presence of something at the end of a statement withif something
orunless something
then useblank?
where needed since it seems to work everywhere.nil?
isblank?
empty?
isblank?
empty?
isnil?
nil?
isempty?
tl;dr -- only use
blank?
&present?
unless you want to distinguish between""
and" "
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?
orobj.present?
instead ofobj.nil?
orobj.empty?
.obj.blank?
handles all typesnil
,''
,[]
,{}
, and returnstrue
if values are not available and returnsfalse
if values are available on any type of object.nil?
is a standard Ruby method that can be called on all objects and returnstrue
if the object isnil
:empty?
is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returnstrue
if these objects contain no element:empty?
cannot be called onnil
objects.blank?
is a Rails method that can be called onnil
objects as well as empty objects..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:Running
.empty?
on something that is nil will throw aNoMethodError
.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..blank?
also evaluates true on strings which are non-empty but contain only whitespace:Rails also provides
.present?
, which returns the negation of.blank?
.Array gotcha:
blank?
will returnfalse
even if all elements of an array are blank. To determine blankness in this case, useall?
withblank?
, for example: