Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby array checking for nil array

Tags:

arrays

null

ruby

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?

like image 441
urjit on rails Avatar asked Apr 16 '13 12:04

urjit on rails


People also ask

How do I check if an array is nil Ruby?

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

Is empty array nil in Ruby?

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.

Is empty array true in Ruby?

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 .

How can you test if an item is included in an array Ruby?

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.


1 Answers

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

like image 178
acsmith Avatar answered Sep 21 '22 02:09

acsmith