我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
当前回答
使用拒绝:
>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
其他回答
在我的项目中,我使用delete:
cities.delete("")
如果你的数组中有混合类型,下面是一个解决方案:
[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]
compact_blank (Rails 6.1+)
如果您正在使用Rails(或独立的ActiveSupport),从6.1版开始,将有一个compact_blank方法从数组中删除空白值。
它使用Object#blank?用于确定一个项目是否为空白。
["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"].compact_blank
# => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
[1, "", nil, 2, " ", [], {}, false, true].compact_blank
# => [1, 2, true]
这里有一个文档链接和一个相关PR链接。
破坏性的变种也是可用的。# compact_blank !看到数组。
如果您使用的是较旧版本的Rails,请检查compact_blank内部实现。
反向移植并不复杂。
def compact_blank
reject(&:blank?)
end
如果你只需要删除nil值,可以考虑使用Ruby内置的Array#compact和Array#compact!方法。
["a", nil, "b", nil, "c", nil].compact
# => ["a", "b", "c"]
cities.reject! { |c| c.blank? }
为什么要用空白?在空的吗?blank可以识别nil,空字符串和空白。例如:
cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }
仍然会返回:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
叫空?On " "将返回false,您可能希望它为true。
注:空白?只能通过Rails访问,Ruby只支持空?
使用严格的join & split更新
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
结果将是:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
注意:这对有空间的城市不起作用