Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails method to detect array of empty strings (["", "",...]) as empty

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.

like image 231
PrathapB Avatar asked Jun 11 '16 17:06

PrathapB


People also ask

How do I check if an array is empty in Ruby on Rails?

To check if a array is empty or not, we can use the built-in empty? method in Ruby. The empty? method returns true if a array is empty; otherwise, it returns false .

How do you remove an empty string from an array in Ruby?

Use compact_blank to remove empty strings from Arrays and Hashes.


2 Answers

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
like image 189
pdobb Avatar answered Oct 12 '22 11:10

pdobb


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
like image 37
Martin Bergek Avatar answered Oct 12 '22 12:10

Martin Bergek