我有下面的数组

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

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

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

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


当前回答

使用严格的join & split更新

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

结果将是:

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

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

其他回答

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

试试这个:

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

纯Ruby:

values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]

使用拒绝:

>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

另一种方法:

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