0

I'm using Ruby 2.4. I have an array of arrays, which looks roughly like this

[[2, 3, 4], ["", "", ""], ["a", "b", nil], [nil, "", nil], [151, "", "abcdef"]]

How would I eliminate all the arrays in the above list if all of their elements are either nil or empty? After applying this function to the above, I'd expect teh result to be

[[2, 3, 4], ["a", "b", nil], [151, "", "abcdef"]]

2 Answers2

1

Something like this using reject and all:

arr.reject { |ar| ar.all? { |e| e.to_s.empty? } }      
 #=> [[2, 3, 4], ["a", "b", nil], [151, "", "abcdef"]]

The key here is nil.to_s.empty? #=> true.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
1

Something like this:

array.select { |sub_array| sub_array.any? { |element| element.present? } }

Or even shorter:

array.select { |sub_array| sub_array.any?(&:present?) }
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • That is true. But since the OP asked several Rails questions during the last days I assume that she is using Rails. – spickermann Jan 12 '17 at 22:05