我有下面的数组

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

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

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

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


当前回答

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

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

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

其他回答

有很多方法可以做到这一点,其中之一是拒绝

noEmptyCities = cities.reject { |c| c.empty? }

你也可以用reject!,这将改变城市的位置。如果拒绝某项,它将返回cities作为返回值,如果没有拒绝,则返回nil。如果你不小心,这可能是一个陷阱(感谢ninja08在评论中指出这一点)。

使用拒绝:

>> 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"]

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

cities.delete("")
cities.reject! { |c| c.blank? }

为什么要用空白?在空的吗?blank可以识别nil,空字符串和空白。例如:

cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }

仍然会返回:

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

叫空?On " "将返回false,您可能希望它为true。

注:空白?只能通过Rails访问,Ruby只支持空?