Check ruby ​​array for nil array

I have a Ruby array and it is nil, but when I check the use of nil?and blank?, it returnsfalse

@a = [""]

@a.nil?
=> false

@a.empty?
=> false

How to check nil condition which returns true?

+5
source share
3 answers

[""]is an array with one element containing an empty String object. [].empty?will return true. @a.nil?returns falsebecause it @ais 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

This last line shows that [].all?it will always return true, because if Array is empty, then by definition all its elements (without elements) fulfill each condition.

+20
source

In ruby ​​you can check it like

[""].all? {|i| i.nil? or i == ""}

,

[""].all? &:blank?
+13
p defined? "" #=> "expression"
p defined? nil #=> "nil"

"", nil, expression. empty non-empty, :

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

Said yours #nil?and #emptygive false. Expected.

+1
source

All Articles