我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
当前回答
已经有很多答案了,但如果你在Rails世界里,这里有另一种方法:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
其他回答
当我想整理一个这样的数组时,我使用:
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
这将删除所有空白或nil元素。
在我的项目中,我使用delete:
cities.delete("")
使用严格的join & split更新
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
结果将是:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
注意:这对有空间的城市不起作用
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
=> ["A", "B", "C"]
这里还有一种方法可以实现这一点
我们可以使用presence和select
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
cities.select(&:presence)
["Kathmandu", "Pokhara", "Dharan", "Butwal"]