Clearing empty strings from an array

I deal with a bunch of arrays of strings and many times when I wrote .delete_if { |str| str.empty? } .delete_if { |str| str.empty? }

Now I know that I can add this method to the array class myself, but I hope there is a built-in way to do this without adding non-standard methods to the base classes. As much fun as adding methods to the base classes, this is not what I want to do for ease of maintenance.

Is there a built-in method for this?

+7
source share
7 answers

There is a short form

 array.delete_if(&:empty?) 
+30
source

Well, there is Array.delete . It returns what deleted (or nil if nothing was deleted), however, which seems awkward. But it performs delivery and does not interrupt for non-row elements:

 ar = ['a', '', 2, 3, ''] p ar.delete('') #=> "" p ar #=> ["a", 2, 3] 
+5
source

You can use this method:

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

Note that you can use the compact method if you need to clear the array from nils.

+5
source

You can do it

 ar = ['a', '', 2, 3, ''] ar = ar.select{|a| a != ""} 

I hope this works for you.

+1
source

You can use .select! but you will still face the same problem.

Instead of modifying the array, you can create a utility class.

0
source

You can try below. Hope this helps you.

array = ["," ", nil, nil, 2,3] array.delete_if (&: blank?) => [2,3]

0
source

If you also want to remove zero:

 arr = ['',"",nil,323] arr.map!{|x|x==''?nil:x}.compact! => [323] 

Map, ternary operator, compact

0
source

All Articles