2

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

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?

jaydel
  • 14,389
  • 14
  • 62
  • 98
  • I still don't understand what you're asking – niceman Jul 11 '16 at 19:16
  • I'm not sure how to clarify it. I wanted to know if there was a method on Array or elsewhere in ruby 2.3 that will remove an object from an array conditionally and return the removed object. As delete_if works, it returns the array of remaining (not deleted) objects and the deleted one disappears into the aether. – jaydel Jul 11 '16 at 19:41
  • 1
    Though inferior to `partition`, `[3,1,4].group_by { |n| n>2 }.values #=> [[3, 4], [1]] ` also works, provided ordering is not an issue. – Cary Swoveland Jul 11 '16 at 20:57
  • thanks for adding another way to do this. I always appreciate seeing multiple solutions--I learn more that way! – jaydel Jul 12 '16 at 12:30

1 Answers1

4

What you want is the partition method:

deleted_items, kept_items = my_array.partition {|a| a.test?}
Hamms
  • 5,016
  • 21
  • 28
  • perfect! thanks. I totally missed that one when going through the Array methods one at a time :/ – jaydel Jul 11 '16 at 19:21