如何在迭代数组时使用 Array#delete?
我有一个数组,我想迭代并删除一些元素。这不起作用:
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 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]
I want a
to be [1, 2]
. How can I get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
a.delete_if { |x| x >= 3 }
请参阅方法文档 这里
更新:
您可以在块中处理x:
a.delete_if { |x| x >= 3 }
See method documentation here
Update:
You can handle x in the block:
您不必从数组中删除,您可以这样过滤它:
You don't have to delete from the array, you can filter it so:
我不久前问过这个问题。
在 Ruby 中迭代时删除?
它不起作用,因为 Ruby 退出了
.each尝试删除某些内容时发生循环。如果您只是想从数组中删除内容,则
delete_if
可以工作,但如果您想要更多控制,我在该线程中提供的解决方案可以工作,尽管它有点丑陋。I asked this question not long ago.
Deleting While Iterating in Ruby?
It's not working because Ruby exits the
.each
loop when attempting to delete something. If you simply want to delete things from the array,delete_if
will work, but if you want more control, the solution I have in that thread works, though it's kind of ugly.另一种方法是使用
reject!
,这可以说更清晰,因为它有一个!
,这意味着“这将改变数组”。唯一的区别是,如果未进行任何更改,reject!
将返回nil
。或者
两者都可以正常工作。
Another way to do it is using
reject!
, which is arguably clearer since it has a!
which means "this will change the array". The only difference is thatreject!
will returnnil
if no changes were made.or
will both work fine.