I have the following array
cities = [\"Kathmandu\", \"Pokhara\", \"\", \"Dharan\", \"Butwal\"]
I want to remove blank elements from the ar
There are already a lot of answers but here is another approach if you're in the Rails world:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
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).
Plain Ruby:
values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? }
cities.reject! { |c| c.blank? }
The reason you want to use blank?
over empty?
is that blank recognizes nil, empty strings, and white space. For example:
cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }
would still return:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
And calling empty?
on " "
will return false
, which you probably want to be true
.
Note: blank?
is only accessible through Rails, Ruby only supports empty?
.
cities.delete_if(&:blank?)
This will remove both nil
values and empty string (""
) values.
For example:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]
cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]