我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
当前回答
有很多方法可以做到这一点,其中之一是拒绝
noEmptyCities = cities.reject { |c| c.empty? }
你也可以用reject!,这将改变城市的位置。如果拒绝某项,它将返回cities作为返回值,如果没有拒绝,则返回nil。如果你不小心,这可能是一个陷阱(感谢ninja08在评论中指出这一点)。
其他回答
试试这个:
puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
当我想整理一个这样的数组时,我使用:
["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
这将删除所有空白或nil元素。
删除空值:
['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"]
如果你的数组中有混合类型,下面是一个解决方案:
[nil,"some string here","",4,3,2]
解决方案:
[nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}
输出:
=> ["some string here", 4, 3, 2]