我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
我有下面的数组
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
我想从数组中删除空白元素,并希望得到以下结果:
cities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
有没有像compact这样不需要循环的方法?
当前回答
以下是对我有效的方法:
[1, "", 2, "hello", nil].reject(&:blank?)
输出:
[1, 2, "hello"]
其他回答
如果你的数组中有混合类型,下面是一个解决方案:
[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"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
另一种方法:
> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
在我的项目中,我使用delete:
cities.delete("")
纯Ruby:
values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]