10

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?

4
  • 2
    [""] is not nil. What are you trying to do? Commented Apr 16, 2013 at 12:54
  • I get the [""] array if this array is coming then it should not go to inner part of the block. Commented Apr 16, 2013 at 12:55
  • 1
    Just do if @a == [""]? Commented Apr 16, 2013 at 12:56
  • 1
    If it is an array, then it is not nil. Commented Apr 16, 2013 at 13:07

3 Answers 3

28

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

Sign up to request clarification or add additional context in comments.

Comments

14

In ruby, you can check like this

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

If you are on rails, you could do

[""].all? &:blank?

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.