Saturday, June 23, 2018

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.


Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...