Difference Between nil?, empty? and blank? in Rails :-
To understand the difference between these three methods you have to look at each of them individually.
In Ruby nil? is a standard method that can be called on all objects and returns true for the nil object and false for anything else.
empty? can be used on either strings, arrays or hashes and it returns true if :-
String length == 0 # length of the String is equal to 0
Array length == 0 # length of the Array is equal to 0
Hash length == 0 # length of the Hash is equal to 0
Applying .empty? on something that is nil will throw a NoMethodError i.e empty cannot be used with nil objects.
That's 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?.
Note:- 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
One difference is that .nil? and .empty? are methods that are provided by the programming language Ruby, whereas .blank? is something added by the Rails web development framework.
0 Comment(s)