How can I tell if an array is either empty or nil?
4 Answers
Without Rails or ActiveSupport,
array.to_a.empty?
6 Comments
sawa
@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.fl00r
I believe it is
NilClass#to_a method also :)Michael Kohl
Splat also works here and I sometimes use it for this purpose:
[*arr].empty?sawa
@Michael I see. That's elegant.
AMIC MING
In Rails if you use
blank?, it will check both .nil? and .empty? |
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
Kris Khaira
Careful with this one.
[" "].blank? and [""].blank? return false.Michael Kohl
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.Joshua Pinter
@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.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
Blankman
I know of those, I was hoping there was a single call that did both (those neg. votes are not from me)
Michael Kohl
@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.Clóvis Valadares Junior
Maybe you have to test arry.nil? first
Mike Lewis
Very true. Changed per your comment.
fl00r
@Michael Kohl, I've figured it out, sorry. Your reason is more solid
blank?.