我有下面的数组

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

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

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

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


当前回答

纯Ruby:

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

其他回答

另一种方法:

> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)

=> ["A", "B", "C"]
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只支持空?

使用严格的join & split更新

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

结果将是:

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

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

纯Ruby:

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