Check for array not empty: any?

后端 未结 6 1677
一整个雨季
一整个雨季 2020-12-12 11:32

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
<         


        
6条回答
  •  天命终不由人
    2020-12-12 12:19

    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:

    1. This is not the same as present? from ActiveSupport.
    2. You might want a custom version for String, that ignores whitespace (like present? does).
    3. You might want the name length? for String or other types where it might be more descriptive.
    4. You might want it custom for Integer and other Numeric types, so that a logical zero returns false.

提交回复
热议问题