A concise explanation of nil v. empty v. blank in Ruby on Rails
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 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
I made this useful table with all the cases:
Just extend Julian's table:
Ref: empty?blank?nil?傻傻分不清楚
链接地址: http://www.djcxy.com/p/4384.html上一篇: 了解Rails真实性令牌