Reputation: 15408
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
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
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
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
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
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
Reputation: 4003
You can do this
ar = ['a', '', 2, 3, '']
ar = ar.select{|a| a != ""}
I hope this will work for you
Upvotes: 1
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
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