Monday, 27 February 2017

ruby - How do I remove blank elements from an array?




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?


Answer



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).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...