Is it bad to check if an array is not empty by using any? method?
a = [1,2,3]
a.any?
=> true
a.clear
a.any?
=> false
<
I don't think it's bad to use any? at all. I use it a lot. It's clear and concise.
However if you are concerned about all nil values throwing it off, then you are really asking if the array has size > 0. In that case, this dead simple extension (NOT optimized, monkey-style) would get you close.
Object.class_eval do
def size?
respond_to?(:size) && size > 0
end
end
> "foo".size?
=> true
> "".size?
=> false
> " ".size?
=> true
> [].size?
=> false
> [11,22].size?
=> true
> [nil].size?
=> true
This is fairly descriptive, logically asking "does this object have a size?". And it's concise, and it doesn't require ActiveSupport. And it's easy to build on.
Some extras to think about:
present? from ActiveSupport.String, that ignores whitespace (like present? does).length? for String or other types where it might be more descriptive.Integer and other Numeric types, so that a logical zero returns false.