ruby 数组检查 nil 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16037597/
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
ruby array checking for nil array
提问by urjit on rails
I have ruby array and it is nilbut when I check using nil?and blank?it returns false
我有红宝石阵列,它是nil,但是当我检查使用nil?和blank?它的回报false
@a = [""]
@a.nil?
=> false
@a.empty?
=> false
How do I check for the nil condition that return true?
如何检查返回 true 的 nil 条件?
回答by acsmith
[""]is an array with a single element containing an empty String object. [].empty?will return true. @a.nil?is returning falsebecause @ais an Array object, not nil.
[""]是一个具有单个元素的数组,其中包含一个空 String 对象。[].empty?会回来true。@a.nil?正在返回,false因为@a是一个 Array 对象,而不是nil。
Examples:
例子:
"".nil? # => false
[].nil? # => false
[""].empty? # => false
[].empty? # => true
[""].all? {|x| x.nil?} # => false
[].all? {|x| x.nil?} # => true
[].all? {|x| x.is_a? Float} # => true
# An even more Rubyish solution
[].all? &:nil? # => true
That last line demonstrates that [].all?will alwaysreturn true, because if an Array is empty then by definition all of its elements (no elements) fulfill every condition.
最后一行表明,[].all?它将始终返回 true,因为如果 Array 为空,那么根据定义,它的所有元素(无元素)都满足所有条件。
回答by acsmith
In ruby, you can check like this
在 ruby 中,你可以这样检查
[""].all? {|i| i.nil? or i == ""}
If you are on rails, you could do
如果你在轨道上,你可以做
[""].all? &:blank?
回答by Arup Rakshit
p defined? "" #=> "expression"
p defined? nil #=> "nil"
The one ""you are thinking as nil, actually an expression. Look at the size of an emptyarray and non-emptyarray as below for more proof:
""您认为的那个nil,实际上是expression. 查看下面的empty数组和non-empty数组的大小以获得更多证明:
p [].size #=> 0
p [""].size #=> 1
Said the your #nil?and #emptygives false. Which is expected.
说你的#nil?和#empty给的false。这是预期的。

