我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
当前回答
在我的项目中,我使用delete:
cities.delete("")
其他回答
你可以试试这个
cities.reject!(&:empty?)
这里还有一种方法可以实现这一点
我们可以使用presence和select
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
cities.select(&:presence)
["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"]
1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
=> ["A", "B", "C"]
使用严格的join & split更新
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
结果将是:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
注意:这对有空间的城市不起作用