如何理解 Ruby 中的 nil vs. empty vs. blank [英] How to understand nil vs. empty vs. blank in Ruby

查看:46
本文介绍了如何理解 Ruby 中的 nil vs. empty vs. blank的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己反复寻找 Ruby on Rails 中 nil?blank?empty? 区别的明确定义.这是我最近的一次:

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here's the closest I've come:

  • blank? 对象为假、空或空白字符串.例如,""" "nil[]{}为空.

  • blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

nil? 对象是 NilClass 的实例.

nil? objects are instances of NilClass.

empty? 对象是特定于类的,并且定义因类而异.没有字符的字符串为空,不包含任何项的数组为空.

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.

是否遗漏了什么,或者可以进行更严格的比较?

Is there anything missing, or a tighter comparison that can be made?

推荐答案

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

.nil? can be used on any object and is true if the object is nil.

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

.empty? can be used on strings, arrays and hashes and returns true if:

  • 字符串长度 == 0
  • 数组长度 == 0
  • 哈希长度 == 0

在一个为零的东西上运行 .empty? 会抛出一个 NoMethodError.

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

这就是 .blank? 的用武之地.它是由 实现的Rails 可以对任何对象进行操作,也可以像 .empty? 一样对字符串、数组和哈希进行操作.

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
0.blank? == false

.blank? 也对非空但只包含空格的字符串求真:

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

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

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

数组问题:blank? 将返回 false 即使数组的所有 元素 都是空的.在这种情况下,要确定空白,请使用 all?blank?,例如:

Array gotcha: 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 

这篇关于如何理解 Ruby 中的 nil vs. empty vs. blank的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆