`
clark1231
  • 浏览: 247637 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

A concise explanation of nil v. empty v. blank in Ruby on Rails

阅读更多

 

.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:

  • String length == 0
  • Array length == 0
  • Hash length == 0

running .empty? on something that is nil will throw a NoMethodError

blank?()

An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank.

This simplifies:

if address.nil? || address.empty?

…to:

if address.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
[].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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics