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

341

我有以下数组

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

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

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

是否有类似于compact的方法可以不使用循环来实现?


4
由于Rails 6现在有了compact_blank方法,因此可能值得更新已接受的答案为@Marian13的答案 - SRack
21个回答

12

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

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

4
“present?”来自于ActiveSupport库。这个方法没有Rails标签,为了使用一个方法而需要额外引入一个gem似乎有些过度了。 - Michael Kohl
1
@Naveed,你应该在前面加上“如果你正在使用RoR”。我不会给它点踩,因为对于初学者来说,这仍然是有用的信息。 - pixelearth

10

这里还有一种方法来实现这个目标

我们可以使用presenceselect

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

cities.select(&:presence)

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

2
谢谢你。我的数组中有一些 " " 元素没有被拒绝方法移除。你的方法可以移除 nil""" " 项。 - iamse7en

10

要删除空值,请执行以下操作:

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

去除空字符串:

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

要同时删除 nil 和空字符串:

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

5
['a', nil, 'b', ''].select(&:present?) 简写的含义是筛选数组中非空(非nil且非blank)的元素。 - Eric Norcross

8

如果您的数组中包含不同类型的元素,这里有一个解决方案:

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

5
你可以试一试。
 cities.reject!(&:empty?)

3
也许你的意思是 cities.reject!(&:blank?)。该代码的作用是删除数组 cities 中为空或只包含空格的元素。 - xguox

2

Shortest way cities.select(&:present?)


2
 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 

删除和排列都是一项昂贵的操作。 - Naveed

1

拒绝和拒绝更新!

注意:我遇到了这个问题,并在irb控制台上使用ruby-3.0.1检查了这些方法。我还检查了ruby文档,但其中没有提到这一点。我不确定从哪个ruby版本开始有这个更改。非常感谢社区的任何帮助。

ruby-3.0.1中,我们可以使用rejectreject!

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

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

无论我们是否有空值,两者都将返回[]

enter image description here


0

另一种方法:

> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]

0

纯Ruby:

values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接