Pages

Friday, January 3, 2014

nil vs empty vs blank in Ruby on Rails

.nil?
.nil? can be used on any object and is true if the object is nil.
.empty?
.empty? can be used on strings, arrays and hashes and returns true if:
  • String length == 0
  • Array length == 0
  • Hash length == 0
Running .empty? on something that is nil will throw a NoMethodError.
.blank?
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
.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?.

No comments:

Post a Comment