jaydel jaydel - 1 year ago 102
Ruby Question

Ruby array delete if and get deleted object

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

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

I can easily reproduce this behavior by doing:

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.

Any thoughts or suggestions?

Answer Source

What you want is the partition method:

deleted_items, kept_items = my_array.partition {|a| a.test?}