如何检查数组中是否存在空集? [英] How do I check if there's a nil set or not in an array?
问题描述
如果我为数组设置了一些nil
值,我似乎无法检查它们.我已经尝试过any?
和empty?
.
If I set some nil
values to an array, I don't seem to be able to check for them. I have tried any?
and empty?
.
array = [nil, nil, nil]
#=> [nil, nil, nil]
array[1].any?
#=> "NoMethodError: undefined method `any?' for nil:NilClass"
推荐答案
any?
遍历容器(如数组),并查看传递给它的每个元素以查看其是否通过测试.如果是,则循环停止并返回true
:
any?
iterates over a container, like an array, and looks at each element passed to it to see if it passes a test. If one does, the loop stops and true
is returned:
ary = [nil, 1]
ary.any?{ |e| e.nil? } # => true
文档很好地解释了这一点:
The documentation explains this well:
将集合的每个元素传递到给定的块.如果该块曾经返回false或nil以外的值,则该方法返回true.如果未提供该块,则Ruby会添加一个{| obj |的隐式块obj}会导致什么?如果至少一个集合成员不是false或nil,则返回true.
Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil.
%w[ant bear cat].any? { |word| word.length >= 3 } #=> true
%w[ant bear cat].any? { |word| word.length >= 4 } #=> true
[nil, true, 99].any? #=> true
any?
是可用于数组以确定是否有 none?
,any?
, all?
.
any?
is one of a number of tests that can be applied to an array to determine if there are none?
, any?
, one?
, or all?
.
ary.one?{ |e| e == 1 } # => true
ary.none?{ |e| e == 2 } # => true
ary.all? { |e| e.nil? } # => false
您的代码失败,因为您尝试对nil值使用不存在的any?
方法,因此出现错误:"NoMethodError:未定义的方法'any?'为nil:NilClass"
Your code fails because you're trying to use a non-existing any?
method for a nil value, hence the error you got: "NoMethodError: undefined method `any?' for nil:NilClass"
ary[0] # => nil
ary.first # => nil
ary.first.respond_to?(:'any?') # => false
您必须注意自己在做什么. ary[0]
或array.first
返回该数组索引处的元素,而不是数组.
You have to pay attention to what you're doing. ary[0]
or array.first
returns the element at that array index, not an array.
empty?
仅检查容器中是否包含元素.换句话说,它的大小> 0吗?
empty?
only checks to see if the container has elements in it. In other words, does it have a size > 0?
ary.empty? # => false
ary.size == 0 # => false
ary.size > 0 # => true
[].empty? # => true
[].size == 0 # => true
[].size > 0 # => false
这篇关于如何检查数组中是否存在空集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!