如何在遍历数组时使用 Array#delete? [英] How can I use Array#delete while iterating over the array?

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

问题描述

我有一个数组,我想迭代并删除一些元素.这不起作用:

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 >= 3 }

查看方法文档这里

更新:

你可以在块中处理 x:

You can handle x in the block:

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

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

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