Idiomatic Ruby filter for nil-or-empty? Idiomatic Ruby filter for nil-or-empty? ruby ruby

Idiomatic Ruby filter for nil-or-empty?


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?endclass NilClass  def blank?    true  endend


The following code should do the trick:

[some_method, some_other_method].reject{|i| i.nil? || i.empty? }

It could be easily used to extend the array class:

class Array  def purge    self.reject{|i| i.nil? || i.empty? }  end end

And then you can just do:

[some_method, some_other_method].purge


monkeypatches accepted? :)

you can try this:

class Array  def tight    self.compact.reject { |i| i.size.zero? }  endendp [nil, 1, ''].tight#=> [1]p ['', nil, 2].tight#=> [2]

it will work with any objects that responds to size, not only with ones that respond to empty?