我有下面的数组

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]

我想从数组中删除空白元素,并希望得到以下结果:

cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

有没有像compact这样不需要循环的方法?


当前回答

最短路径城市。select(&:present?)

其他回答

最短路径城市。select(&:present?)

 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 

使用严格的join & split更新

cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split

结果将是:

["Kathmandu", "Pokhara", "Dharan", "Butwal"]

注意:这对有空间的城市不起作用

另一种方法:

> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]

在我的项目中,我使用delete:

cities.delete("")