Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have to sort through a (rows)array of (row)arrays. The (row)arrays contain an arbitrary number of strings. If a (row)array contains only empty strings I want to remove it from the (rows)array.

I'm 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 it?

like image 229
Undistraction Avatar asked Dec 08 '22 20:12

Undistraction


2 Answers

Slightly more concise:

rows.reject! { |row| row.all?(&:empty?) }
like image 58
Alex D Avatar answered May 25 '23 09:05

Alex D


Modifying an array while you iterate though it is not a good idea - you may find your code skips certain elements or does weird stuff. I'd do

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

We reject a row if the block row_element.empty? evaluates to true for all elements in the row. It's well worth getting familiar with all of the methods in Enumerable, they're very handy for this sort of task.

like image 33
Frederick Cheung Avatar answered May 25 '23 08:05

Frederick Cheung