如何删除Ruby中数组中满足条件的所有元素? [英] How to remove all elements that satisfy a condition in array in Ruby?

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

问题描述

我如何在 Ruby 中实现它?有没有一行代码技术?假设我想删除整数数组中小于 3 的所有元素.

How can I implement this in Ruby? Is there any one line of code technique? Let's say I want to get rid of all the elements which are less than 3 of an integer array.

推荐答案

你可以使用 new_array = array.reject {|x|×<3} (reject 返回一个新数组) 或 array.reject!{|x|×<3}(reject! 又名 delete_if 就地修改数组).

You can use either new_array = array.reject {|x| x < 3} (reject returns a new array) or array.reject! {|x| x < 3} (reject! aka delete_if modifies the array in place).

还有(更常见的)select 方法,它的作用类似于 reject 不同之处在于您指定条件来保留元素,而不是拒绝它们(即获取去掉小于 3 的元素,你可以使用 new_array = array.select {|x| x >= 3}).

There's also the (somewhat more common) select method, which acts like reject except that you specify the condition to keep elements, not to reject them (i.e. to get rid of the elements less than 3, you'd use new_array = array.select {|x| x >= 3}).

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

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