I have the following array
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
I want to remove blank elements from the array and want the following result:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Is there any method like compact
that will do it without loops?
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
C++ arrays does not have any empty elements. All elements has a value. One approach is to use a sentinel value. Simply pick a value that fits in an int and use that to denote empty.
There are many ways to do this, one is reject
noEmptyCities = cities.reject { |c| c.empty? }
You can also use reject!
, which will modify cities
in place. It will either return cities
as its return value if it rejected something, or nil
if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).
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