我有下面的数组

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

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

其他回答

使用严格的join & split更新

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

结果将是:

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

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

最明确的

cities.delete_if(&:blank?)

这将删除nil值和空字符串("")值。

例如:

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

cities.delete_if(&:blank?)
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

删除空值:

 ['a', nil, 'b'].compact  ## o/p =>  ["a", "b"]

删除空字符串:

   ['a', 'b', ''].select{ |a| !a.empty? } ## o/p => ["a", "b"]

删除空字符串和空字符串:

['a', nil, 'b', ''].select{ |a| a.present? }  ## o/p => ["a", "b"]

使用拒绝:

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

以下是对我有效的方法:

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

输出:

[1, 2, "hello"]