Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove blank elements from an array?

Tags:

arrays

ruby

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?

like image 664
ashisrai_ Avatar asked May 04 '11 04:05

ashisrai_


People also ask

How do you delete empty elements in an array?

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.

Can you have an empty element in an array?

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.


1 Answers

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

like image 197
Matt Greer Avatar answered Sep 22 '22 01:09

Matt Greer