rubyidiomsenumerable

Idiomatic Ruby filter for nil-or-empty?


I'm looking for a more idiomatic way to filter out nil-or-empty elements of an array.

I have many methods of the form:

def joined
    [some_method, some_other_method].compact.reject(&:empty?).join(' - ')
end

This will take the result of some_method and some_other_method and return only the one(s) that are both non-nil (compact is essentially equivalent to reject(&:nil?)) and non-empty.

Is there anything in Array or Enumerable that gets the same thing in one shot?


Solution

  • In Rails, you can do reject(&:blank?), or equivalently, select(&:present?).

    If this is not for a Rails app, and you do this a lot, I'd advise you to define your own helper on String or whatever else you are filtering.

    class String
      alias :blank? :empty?
    end
    
    class NilClass
      def blank?
        true
      end
    end