Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing Empty Strings from an Array

Tags:

arrays

ruby

I'm dealing with a bunch of arrays made of strings and many a times I've written .delete_if { |str| str.empty? }

Now, I know I can add this method to the array class myself but I'm hoping there's a built in way to do this without having non-standard methods added to base classes. As much fun as adding methods to base classes is, it's not something I wanna do for maintainability reasons.

Is there a built in method to handle this?

like image 600
Drew Avatar asked Apr 25 '11 21:04

Drew


People also ask

How do I remove empty elements from a list?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.


2 Answers

There is a short form

array.delete_if(&:empty?)
like image 142
fl00r Avatar answered Oct 05 '22 19:10

fl00r


You can use this method:

    1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
    => `["A", "B", "C"]`

Please note that you can use the compact method if you only got to clear an array from nils.

like image 29
sidney Avatar answered Oct 05 '22 19:10

sidney