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"
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"
If you want to check if the array includes nil:
All this methods accepts an optional block for the boolean evaluation.
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 andtrue
is returned:The documentation explains this well:
any?
is one of a number of tests that can be applied to an array to determine if there arenone?
,any?
,one?
, orall?
.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"You have to pay attention to what you're doing.
ary[0]
orarray.first
returns the element at that array index, not an array.empty?
only checks to see if the container has elements in it. In other words, does it have a size > 0?You can turn nil values into booleans this way to check for them
However, using any? checks for the existence of something. You can use
To check if there are any values that evaluate to
false
as anil
value does. Be careful if you might have afalse
value in your array though because it will also be evaluated astrue
using this this method.Or you could just use:
As other posters have suggested
Your problem is that you are calling the
any?
method on nil and not on an array.