我有下面的数组

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

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

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

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


当前回答

更新在拒绝和拒绝!

注意:我遇到了这个问题,并在irb控制台上用ruby-3.0.1检查了这些方法。我也检查了ruby文档,但没有提到这一点。我不确定从哪个ruby版本 变化就在那里。非常感谢来自社区的任何帮助。

在ruby-3.0.1中,我们可以使用reject或reject!

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

或简写

cities.reject(&:empty?)
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

无论我们是否有一个空值,两者都会返回[]?

其他回答

如果你的数组中有混合类型,下面是一个解决方案:

[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.reject!(&:empty?)

更新在拒绝和拒绝!

注意:我遇到了这个问题,并在irb控制台上用ruby-3.0.1检查了这些方法。我也检查了ruby文档,但没有提到这一点。我不确定从哪个ruby版本 变化就在那里。非常感谢来自社区的任何帮助。

在ruby-3.0.1中,我们可以使用reject或reject!

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

或简写

cities.reject(&:empty?)
=> ["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"].delete_if {|c| c.empty? }