I find myself repeatedly looking for a clear definition of the differences of nil?
, blank?
, and empty?
in Ruby on Rails. Here\'s the
exists?
method can be used to check whether the data exists in the database or not. It returns boolean values either true
or false
.
Just a little note about the any?
recommendation: He's right that it's generally equivalent to !empty?
. However, any?
will return true
to a string of just whitespace (ala " "
).
And of course, see the 1.9 comment above, too.
.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 a NoMethodError
.
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.
nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false
.blank?
also evaluates true on strings which are non-empty but contain only whitespace:
" ".blank? == true
" ".empty? == false
Rails also provides .present?
, which returns the negation of .blank?
.
Array gotcha: blank?
will return false
even if all elements of an array are blank. To determine blankness in this case, use all?
with blank?
, for example:
[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true
Just extend Julian's table:
Ref: empty?blank?nil?傻傻分不清楚
nil?
can be used on any object. It determines if the object has any value or not, including 'blank' values.
For example:
example = nil
example.nil? # true
"".nil? # false
Basically nil?
will only ever return true if the object is in fact equal to 'nil'.
empty?
is only called on objects that are considered a collection. This includes things like strings (a collection of characters), hashes (a collection of key/value pairs) and arrays (a collection of arbitrary objects). empty?
returns true is there are no items in the collection.
For example:
"".empty? # true
"hi".empty? # false
{}.empty? # true
{"" => ""}.empty? # false
[].empty? # true
[nil].empty? # false
nil.empty? # NoMethodError: undefined method `empty?' for nil:NilClass
Notice that empty?
can't be called on nil objects as nil objects are not a collection and it will raise an exception.
Also notice that even if the items in a collection are blank, it does not mean a collection is empty.
blank?
is basically a combination of nil?
and empty?
It's useful for checking objects that you assume are collections, but could also be nil.
Quick tip: !obj.blank? == obj.present?
Can be handy/easier on the eyes in some expressions