如何使用阵列#删除在遍历数组了吗? [英] How can I use Array#delete while iterating over the array?

查看:102
本文介绍了如何使用阵列#删除在遍历数组了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想遍历并删除了一些元素的数组。这不工作:

I have an array that I want to iterate over and delete some of the elements. This doesn't work:

a = [1, 2, 3, 4, 5]
a.each do |x|
  next if x < 3
  a.delete x
  # do something with x
end
a #=> [1, 2, 4]

我想 A [1,2] 。我怎样才能解决这个得到什么?

I want a to be [1, 2]. How can I get around this?

推荐答案

a.delete_if {| X | X - GT; = 3}

在这里见方法的文档

更新:

您可以在块处理X:

a.delete_if do |element|
  if element >= 3
    do_something_with(element)
    true # Make sure the if statement returns true, so it gets marked for deletion
  end
end

这篇关于如何使用阵列#删除在遍历数组了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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