我有以下数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
是否有类似于compact
的方法可以不使用循环来实现?
已经有很多答案了,但如果你在Rails世界中,这里是另一种方法:
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
ActiveSupport
库。这个方法没有Rails标签,为了使用一个方法而需要额外引入一个gem似乎有些过度了。 - Michael Kohl这里还有一种方法来实现这个目标
我们可以使用presence
和select
cities = ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"]
cities.select(&:presence)
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
" "
元素没有被拒绝方法移除。你的方法可以移除 nil
、""
或 " "
项。 - iamse7en要删除空值,请执行以下操作:
['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"]
['a', nil, 'b', ''].select(&:present?)
简写的含义是筛选数组中非空(非nil且非blank)的元素。 - Eric Norcross如果您的数组中包含不同类型的元素,这里有一个解决方案:
[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?)
cities.reject!(&:blank?)
。该代码的作用是删除数组 cities
中为空或只包含空格的元素。 - xguoxShortest way cities.select(&:present?)
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.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","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
纯Ruby:
values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]
compact_blank
方法,因此可能值得更新已接受的答案为@Marian13的答案。 - SRack