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?
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.
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