I have the following array
cities = [\"Kathmandu\", \"Pokhara\", \"\", \"Dharan\", \"Butwal\"]
I want to remove blank elements from the ar
Shortest way cities.select(&:present?)
If you are using Rails
(or a standalone ActiveSupport
), starting from version 6.1
, there is a compact_blank method which removes blank
values from arrays.
It uses Object#blank? under the hood for determining if an item is blank.
["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"].compact_blank
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# => [1, 2, true]
Here is a link to the docs and a link to the relative PR.
A destructive variant is also available. See Array#compact_blank!.
If you need to remove only nil
values,
please, consider using Ruby build-in Array#compact and Array#compact! methods.
["a", nil, "b", nil, "c", nil].compact
# => ["a", "b", "c"]
Try this:
puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
Use reject
:
>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Update with a strict with join
& split
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
Result will be:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Note that: this doesn't work with a city with spaces
When I want to tidy up an array like this I use:
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
This will remove all blank or nil elements.