.nil?、.blank 之间的区别?和.空? [英] Difference between .nil?, .blank? and .empty?

查看:51
本文介绍了.nil?、.blank 之间的区别?和.空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
nil v 的简明解释. empty v. 在 Ruby on Rails 中的空白

谁能告诉我 nil?blank?empty? 在 Ruby 中的区别?

Can anyone tell me the difference between nil?, blank? and empty? in Ruby?

推荐答案

在 Ruby 中,nil 在一个对象中(NilClass 类的单个实例).这意味着可以对其调用方法.nil? 是 Ruby 中的标准方法,可以在 所有 对象上调用,并为 nil 对象返回 truefalse 其他任何东西.

In Ruby, nil in an object (a single instance of the class NilClass). This means that methods can be called on it. nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else.

empty?某些 对象(如数组、哈希和字符串)上的标准 Ruby 方法.它的确切行为将取决于特定对象,但如果对象不包含任何元素,它通常返回 true.

empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true if the object contains no elements.

blank? 不是标准的 Ruby 方法,而是由 Rails 添加到所有对象中,并为 niltruecode>、false、空或空白字符串.

blank? is not a standard Ruby method but is added to all objects by Rails and returns true for nil, false, empty, or a whitespace string.

因为 empty? 不是为所有对象定义的,如果你在 nil 上调用 empty?,你会得到 NoMethodErrorcode> 以避免必须编写诸如 if x.nil 之类的东西?||x.empty? Rails 添加了 blank? 方法.

Because empty? is not defined for all objects you would get a NoMethodError if you called empty? on nil so to avoid having to write things like if x.nil? || x.empty? Rails adds the blank? method.

回答后发现了一个之前的问题,如何理解 Rails(和 Ruby)中的 nil 与空与空白",所以你也应该检查一下答案.

After answering, I found an earlier question, "How to understand nil vs. empty vs. blank in Rails (and Ruby)", so you should check the answers to that too.

这篇关于.nil?、.blank 之间的区别?和.空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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