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?
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.
There is a short form
array.delete_if(&:empty?)
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.
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