Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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?
by

2 Answers

vishaljlf39
Here is what works for me:
[1, "", 2, "hello", nil].reject(&:blank?)


output:
[1, 2, "hello"]
pankajshivnani123
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.

Login / Signup to Answer the Question.