A more elegant way to reject an array if it contains only empty lines

I need to sort an array (of rows) of arrays (rows). Arrays (strings) contain an arbitrary number of strings. If the array (row) contains only empty rows, I want to remove it from the array (rows).

I am currently doing this:

rows.each do |row| row.each_index do |i| if row[i].length > 0 break elsif i == row.count-1 rows.delete(row) end end end 

But is there a more elegant way to do this?

+4
source share
6 answers

A bit more concise:

 rows.reject! { |row| row.all?(&:empty?) } 
+5
source

Changing the array upon repetition, although this is not a good idea - you may find that your code skips certain elements or does strange things. I would do

 rows.reject! {|row| row.all? {|row_element| row_element.empty?}} 

We reject the row if row_element.empty? block row_element.empty? evaluates to true for all elements in the row. Familiar with all the methods in Enumerable, they are very convenient for this kind of task.

+4
source

when using rails:

 ! rows.any?(&:present?) 
+4
source

You can use compact.uniq or compact . If your arrays are nil , compact will result in empty arrays, so you can check this as follows:

 row.compact.size == 0 

if the line contains empty lines "", you can check it as follows:

 row.compact.uniq.first.blank? and row.size == 1 
+2
source
  rows.select{|row| row.compact.count >0} 
0
source

Here: rows.all?(&:blank?) .

-1
source

Source: https://habr.com/ru/post/1438478/


All Articles