blank?是什么

Published on:

Rails中会常用到的blank? 方法
blank?方法是Rails而非Ruby中的方法. 基本上它实现了nil? empty?的作用. 下面是来自Rails API文档中的介绍:
“An object is blank if it‘s false, empty, or a whitespace string.

For example, "", " ", nil, [], and {} are blank.”
举例来说, 我经常会在模型中赋值的场景调用blank?方法. 回想之前的例子-- dog哈希表, 我们可以这样来简化检验值

[ruby] view plain copy
script/console >>

dog = {:name => "Beauregard"}
puts "What kind?" if dog[:breed].blank?
=> What kind?

dog = {:name => "Beauregard", :breed => ""}
puts "What kind?" if dog[:breed].blank?
=> What kind?

可以看到 .blank? 的结果 相当于 .ni? + .empty?

Comments

comments powered by Disqus