rhunal
rhunal

Reputation: 415

array.nil? when array having only multiple `nil` values

Consider an array having only one value nil

array = [nil]

Is there any better way to check whether an array is nil or not, like array.nil??

This works:

array == [nil]

But what if there are multiple nil values in the array?

array = [nil, nil, nil]

Below is the requirement:

array = [1, 2] if array.nil?

array.nil? should also give 'true' when array = [nil, nil, nil]

Upvotes: 1

Views: 299

Answers (3)

Bartosz Pietraszko
Bartosz Pietraszko

Reputation: 1407

One of possible ways is to remove nil values with .compact and check if the result is empty? .

array = [1, 2] if array.compact.empty?

Upvotes: 0

axiac
axiac

Reputation: 72177

You can use Array#any? to check if the array contains at least one value that is not false or nil:

array = [1,2] unless array.any?

If array is allowed to contain false and you are interested only in nil then Array#any? needs a block:

array = [1,2] unless array.any?{|i| !i.nil?}

Update

As @mu-is-too-short suggests, a better version is:

array = [1,2] if array.all?(&:nil?)

It does exactly what you need: Enumerable#all? returns true if the block returns a true-ish value for all elements of the array.

Upvotes: 3

kabanus
kabanus

Reputation: 25895

One option is to uniquify your array and then do what you were already doing:

array.uniq == [nil]

So if array is any amount of nils it will be true. On the other hand:

array.nil?

Checks whether array itself is nil, which is not the same as an array containing nil elements.

Upvotes: 2

Related Questions