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?
nil?
can be used on any object. It determines if the object has any value or not, including 'blank' values.For example:
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:
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 ofnil?
andempty?
It's useful for checking objects that you assume are collections, but could also be nil.Just extend Julian's table:
Ref: empty?blank?nil?傻傻分不清楚