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?
exists?
method can be used to check whether the data exists in the database or not. It returns boolean values eithertrue
orfalse
.A special case is when trying to assess if a boolean value is nil:
In this case the recommendation would be to use
.nil?
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:
one could also do:
I made this useful table with all the cases:
blank?
,present?
are provided by Rails.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.Just a little note about the
any?
recommendation: He's right that it's generally equivalent to!empty?
. However,any?
will returntrue
to a string of just whitespace (ala" "
).And of course, see the 1.9 comment above, too.