我有下面的数组

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

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

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

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


当前回答

1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)

=> ["A", "B", "C"]

其他回答

试试这个:

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

使用拒绝:

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

以下是对我有效的方法:

[1, "", 2, "hello", nil].reject(&:blank?)

输出:

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

当我想整理一个这样的数组时,我使用:

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

这将删除所有空白或nil元素。