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.
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 .
Use compact_blank to remove empty strings from Arrays and Hashes.
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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With