45

How can I tell if an array is either empty or nil?

1
  • 6
    Array cannot be nil. Variable can be nil or an Array or whatever else. But an Array can be only an Array. You can use blank?. Commented Apr 17, 2011 at 16:46

4 Answers 4

54

Without Rails or ActiveSupport,

array.to_a.empty?
Sign up to request clarification or add additional context in comments.

6 Comments

@fl00r Thanks. This is actually, I believe, is the purpose of the built in method Array#to_a. I can't think of other uses of it.
I believe it is NilClass#to_a method also :)
Splat also works here and I sometimes use it for this purpose: [*arr].empty?
@Michael I see. That's elegant.
In Rails if you use blank?, it will check both .nil? and .empty?
|
38

There's no built-in Ruby method that does this, but ActiveSupport's blank does:

>> require "active_support/core_ext/object/blank" #=> true
>> nil.blank? #=> true
>> [].blank? #=> true

3 Comments

Careful with this one. [" "].blank? and [""].blank? return false.
Nothing to be careful about. You're calling blank? on an instance of array and said array is neither empty nor nil. If that's not what you want use [''].all?(&:blank?) instead.
@KrisKhaira If you want to catch empty Strings as well (and are using Rails) you can also use [ " ", "" ].compact_blank.empty? #=> true. I actually like @Michael Kohl's .all?(&:blank?) better if you don't want to modify the array, though.
13

You can just use the Array#empty? and Object#nil? methods in conjunction with an OR.

arr.nil? || arr.empty?

This will return true of array is empty or the array value is nil.

5 Comments

I know of those, I was hoping there was a single call that did both (those neg. votes are not from me)
@aromero: The downvote was probably because if arr really is nil, the empty? check will raise a NoMethodError. If you reverse the order it's fine, because the logical expression will short-circuit.
Maybe you have to test arry.nil? first
Very true. Changed per your comment.
@Michael Kohl, I've figured it out, sorry. Your reason is more solid
5

To check whether array is empty one can use 'empty?' inbuilt method as follows,

array.empty? # returns true/false

To check whether array is nil (If not initialized or set to nil)

array.nil? # returns true/false

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.