I have ruby array and it is nil
but when I check using nil?
and blank?
it returns false
@a = [""]
@a.nil?
=> false
@a.empty?
=> false
How do I check for the nil condition that return true?
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
How can I tell if an array is either empty or nil? Array cannot be nil. Variable can be nil or an Array or whatever else. But an Array can be only an Array.
All & Empty Arraysmethod will return true if you call it on an empty array. Explanation: Since NO elements are false then all elements must be true .
This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.
[""]
is an array with a single element containing an empty String object. [].empty?
will return true
. @a.nil?
is returning false
because @a
is an Array object, not 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 always return true, because if an Array is empty then by definition all of its elements (no elements) fulfill every condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With