我如何从数组中删除空白元? [英] How do I remove blank elements from an array?

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

问题描述

我有以下阵列

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

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

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

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

有没有像的任何方法紧凑会做没有循环?

推荐答案

有很多方法可以做到这一点,一个是拒绝

There are many ways to do this, one is reject

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

您也可以使用拒绝!,它会修改城市到位。它将要么返回城市作为它的返回值,如果它拒绝的东西,或者如果没有拒绝制成。这可以是一个疑难杂症,如果你不小心(感谢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).

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆