Search code examples
rubyarraysnull

How do I check if there's a nil set or not in an array?


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"

Solution

  • 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:

    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? 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
    

    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
    

    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? 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