Ruby数组删除if并获取删除的对象 [英] Ruby array delete if and get deleted object
问题描述
因此,在这种情况下,我需要有条件地从数组中删除某些内容,这意味着我想遍历数组中的项目并进行测试,然后删除通过测试的内容,然后再获取那删除的项目回来。如果我排除此条件的条件,则 Array#delete
基本上会执行我想要的操作-返回已删除的项目,但不能有条件地删除。另一方面,delete_if有条件地删除该项目,但将剩余的项目返回到数组中。
So I have this situation where I need to delete something from an array conditionally, meaning that I want to go through the items in the array and do a test and delete the one that passes the test, and then I want to get that deleted item back. If I exclude the conditional aspect of this then Array#delete
does what I want basically--returns the deleted item, but can't delete conditionally. On the other hand delete_if removes the item conditionally, but returns the remaining items back in an array.
出于这个问题的目的,假定使用以下类:
For the purposes of this question assume the following class:
class Foo
def test?
#returns true or false
end
end
我可以
index = my_array.index {|a| a.test?}
item_to_delete = my_array[index]
my_array.delete item_to_delete
但是我希望能找到类似的东西:
But I was hoping to find something like:
deleted_item = my_array.delete_if_and_return_deleted {|a| a.test?}
我不必为遍历数组多次而感到兴奋完成此操作:/首先找到目标的索引,第二次获取目标,第三次删除目标。
I'm not thrilled about having to go through the array multiple times to get this done :/ first to find the target's index, second to get the target and third to remove the target. Ick.
有什么想法或建议吗?
推荐答案
您想要什么是分区方法:
deleted_items, kept_items = my_array.partition {|a| a.test?}
这篇关于Ruby数组删除if并获取删除的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!