Ruby-on-rails 什么时候使用 nil、blank、empty?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1654960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use nil, blank, empty?
提问by David C
Is there any guidelines on how to differentiate between .nil?, .blank?and .empty??
是否有关于如何区分.nil?,.blank?和 的指南.empty??
I'm generally always confused as to when to use them in my application as they all seem to mean the same thing but have different meanings.
我通常总是对何时在我的应用程序中使用它们感到困惑,因为它们似乎都意味着相同的事情但具有不同的含义。
Does anyone have any cheat sheet on the gory details?
有人有关于血腥细节的备忘单吗?
回答by Julian Popov
Here I made this useful table with all the cases
在这里,我用所有案例制作了这张有用的表格
回答by Karmen Blake
nil?- checks to see if variable is referencing an object or notempty?- may be used to check on various object types like empty string ""or empty array []blank?- checks fornil?orempty?.
回答by cwninja
nil?is defined on allObjects, it only returnstrueon thenilsingleton.blank?is defined on all objects too, it returnstrueif the object also responds toempty?and is empty, or is afalsetype value (!objectis alwaystrue).empty?is defined on several collection objects, and istrueif it has no elements. It is also defined onString.
nil?在 all 上定义Objects,它只true在nil单例上返回。blank?也定义在所有对象上,true如果对象也响应empty?并且为空,或者是false类型值(!object总是true),则返回。empty?在几个集合对象上定义,true如果它没有元素。它也在 上定义String。
note that blank?is ActiveSupportand not in Rails 1.8.
注意,blank?是ActiveSupport而不是Rails的1.8。
回答by Andrew Hare
I found a good explanation here:
我在这里找到了一个很好的解释:
nil? tests whether the object is exactly nil, that is whether it is the one and only want instance of NilClass.
empty? is a method some objects respond to. You need to check the documentation for each case. For example, and empty array is one that is not nil (it is an array right?) and has no elements. An empty string is one that is not nil (it is a string right?) and has no bytes, nothing.
The blank? method you ask for does not belong to Ruby, it is a Rails extension: http://api.rubyonrails.com/classes/Object.html#M000011.
零?测试对象是否完全为零,即它是否是 NilClass 的唯一想要的实例。
空的?是一些对象响应的方法。您需要检查每个案例的文档。例如,空数组是一个不为 nil 的数组(它是一个数组,对吗?)并且没有元素。一个空字符串是一个不为零的字符串(它是一个字符串,对吗?)并且没有字节,什么都没有。
空白?您要求的方法不属于 Ruby,它是一个 Rails 扩展:http: //api.rubyonrails.com/classes/Object.html#M000011。
If you click through to the link at the end of that post you will find that the blank?method simply combines the nil?and empty?method calls.
如果您单击该帖子末尾的链接,您会发现该blank?方法只是将nil?和empty?方法调用组合在一起。

