问题

我发现自己在Ruby on Rails中反复寻找对 nil?, blank? empty? .这是我最近来的:

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

有没有什么缺失,或者可以进行更严格的比较?



解决方法

.nil?可用于任何对象,如果对象为nil,则为true.

.empty?可用于字符串,数组和哈希,并在以下情况下返回true:

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

在nil会运行 .empty?会抛出 NoMethodError .

这是 .blank?的作用.它是实现的Rails ,并且可以对任何对象以及字符串,数组和哈希上的 .empty?进行操作.

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank?在非空但仅包含空格的字符串上计算true:

"  ".blank? == true
"  ".empty? == false

Rails还提供 .present?,它返回否定of .blank?.

Array getcha: blank?会返回 false ,即使数组的所有元素为空.在这种情况下确定空白,使用 all? blank?,例如:

[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true 



相关问题推荐