本文介绍了如何从数组中删除空白元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组

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

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

I want to remove blank elements from the array and want the following result:

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

有没有像 compact 这样的方法可以在没有循环的情况下做到这一点?

Is there any method like compact that will do it without loops?

推荐答案

有很多方法可以做到这一点,一种是reject

There are many ways to do this, one is reject

noEmptyCities = cities.reject { |c| c.empty? }

您也可以使用reject!,它会在适当的位置修改cities.如果拒绝某些内容,它将返回 cities 作为其返回值,或者如果没有拒绝,则返回 nil.如果您不小心,这可能是一个陷阱(感谢 ninja08 在评论中指出这一点).

You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).

这篇关于如何从数组中删除空白元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:26