ruby array checking for nil array

38,916

Solution 1

[""] 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.

Solution 2

p defined? "" #=> "expression"
p defined? nil #=> "nil"

The one "" you are thinking as nil, actually an expression. Look at the size of an empty array and non-empty array as below for more proof:

p [].size #=> 0
p [""].size #=> 1

Said the your #nil? and #empty gives false. Which is expected.

Share:
38,916
urjit on rails
Author by

urjit on rails

Updated on July 23, 2022

Comments

  • urjit on rails
    urjit on rails almost 2 years

    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?