我有下面的数组

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

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

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

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


当前回答

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

cities.delete("")

其他回答

这里还有一种方法可以实现这一点

我们可以使用presence和select

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

cities.select(&:presence)

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

试试这个:

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

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

cities.delete("")

你可以试试这个

 cities.reject!(&:empty?)
 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? }