如何从数组中删除空白元素?

我有以下数组

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

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

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

有什么办法像compact ,将做到没有循环?

有很多方法可以做到这一点,一个是reject

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

你也可以使用reject! ,这将修改cities 。 如果拒绝,它将返回cities作为回报价值;如果不拒绝,则返回nil 。 如果你不小心,这可能是一个陷阱(感谢ninja08在评论中指出这一点)。

 1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?) => ["A", "B", "C"] 

在我的项目中,我使用delete

 cities.delete("") 

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

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

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

这是对我有用的东西:

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

输出:

 [1, 2, "hello"] 

最明确的

 cities.delete_if(&:blank?) 

这将删除nil值和空string( "" )值。

例如:

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

尝试这个:

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

使用reject

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

你想使用blank?的原因blank?empty? 是空白识别零,空string和空格。 例如:

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

仍然会返回:

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

并呼吁empty?" "将返回false ,你可能希望是true

注意: blank? 只能通过Rails访问,Ruby只支持empty?

已经有很多答案,但是如果你在Rails世界里,这是另一种方法:

  cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present? 

这是另一种方法来实现这一点

我们可以使用presenceselect

 cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"] cities.select(&:presence) ["Kathmandu", "Pokhara", "Dharan", "Butwal"] 

如果你的数组中有混合types,这里是一个解决scheme:

 [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] 
  cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 

你可以试试这个

  cities.reject!(&:empty?) 

最短路线cities.select(&:present?)

更新与严格的joinsplit

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

结果将是:

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