13

Is there a rails function to detect ["", "", ...] (i.e. An array containing only empty string or strings) as empty

My requirement:

[""].foo? => true

["", ""].foo? => true

["lorem"].foo? => false

["", "ipsum"].foo? => false

I tried using array.reject!(&:empty?).blank?. It worked, but this changed my array. I don't want my array to be changed. Please help me find a compact method.

PrathapB
  • 382
  • 1
  • 4
  • 15

2 Answers2

24

There isn't a single method, but you can use .all?.

["", nil].all?(&:blank?) # => true
["ipsum", ""].all?(&:blank?) # => false

Or you can get the opposite result with .any?.

["", nil].any?(&:present?) # => false
["lorem", ""].any?(&:present?) # => true
pdobb
  • 17,688
  • 5
  • 59
  • 74
  • 1
    I wonder if `.all?` would be more performant on large Arrays (if it returns immediately when it finds something other than the expected value)? – Joshua Pinter Jan 07 '20 at 04:38
3

OP was asking for a solution for Rails but I came here while looking for a generic Ruby solutions. Since present? and blank? are both Rails extensions the above solution did not work for me (unless I pull in ActiveSupport which I didn't want).

May I instead offer a simpler solution:

[nil, nil].join.empty? # => true
["", nil].join.empty? # => true
["lorem", nil].join.empty? # => false
Martin Bergek
  • 321
  • 3
  • 10