Drew
Drew

Reputation: 15408

Clearing Empty Strings from an Array

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?

Upvotes: 13

Views: 14384

Answers (9)

David Hempy
David Hempy

Reputation: 6207

As of Rails 5.2, Enumerable now supports .compact_blank, which does precisely what you're asking for:

[1, "", nil, 2, " ", [], {}, false, true, 3].compact_blank
# =>  [1, 2, true, 3]

It works on hashes as well, removing pairs that have a blank value.

Docs: https://apidock.com/rails/Enumerable/compact_blank

Upvotes: 0

Radin Reth
Radin Reth

Reputation: 867

For simple work around:

my_array = ['a', '', 2, 3, '']
compact_array = my_array.select(&:present?)
# => ["a", 2, 3]

Here:

We select only item of array that ruby think it's present while nil and "" is not present? in ruby

Upvotes: 0

xxjjnn
xxjjnn

Reputation: 15239

If you also want to remove nil:

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

=> [323]

Map, ternary operator, compact

Upvotes: 0

Rajasekhar Bammidi
Rajasekhar Bammidi

Reputation: 113

You can try below solution. I hope it ll help you.

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

Upvotes: 0

fl00r
fl00r

Reputation: 83680

There is a short form

array.delete_if(&:empty?)

Upvotes: 40

sidney
sidney

Reputation: 2714

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.

Upvotes: 8

Asnad Atta
Asnad Atta

Reputation: 4003

You can do this

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

I hope this will work for you

Upvotes: 1

steenslag
steenslag

Reputation: 80065

Well, there is Array.delete. It returns what's deleted (or nil if nothing is deleted) however, which feels clumsy. But it does deliver and does not fail on non-string elements:

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

Upvotes: 5

JSager
JSager

Reputation: 1430

You can use .select! but you're still going to run into the same problem.

Instead of modifying array, you could create a utility class instead.

Upvotes: 0

Related Questions