从数组 Ruby 中删除元素 [英] Removing elements from array Ruby

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

问题描述

假设我试图从数组 a = [1,1,1,2,2,3] 中删除元素.如果我执行以下操作:

Let's say I am trying to remove elements from array a = [1,1,1,2,2,3]. If I perform the following:

b = a - [1,3]

然后我会得到:

b = [2,2]

但是,我希望结果是

b = [1,1,2,2]

即我只删除减法向量中每个元素的一个实例,而不是所有情况.Ruby 有没有简单的方法可以做到这一点?

i.e. I only remove one instance of each element in the subtracted vector not all cases. Is there a simple way in Ruby to do this?

推荐答案

您可以:

a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
    a.delete_at(a.index(del))
end

结果:[1, 1, 2, 2]

result : [1, 1, 2, 2]

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

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