Is there a quick Ruby or Rails method to delete an element from an Array based on a condition provided in a block and then return that element?
Let’s say, given:
e1.good? # false
e2.good? # true
e3.good? # true
a = [e1, e2, e3]
Is there a method delete_and_return_if doing this:
a.delete_and_return_if { |e| e.good? } # delete e2 from a and returns e2
[e1].delete_and_return_if { |e| e.good? } # returns nil
Or at least is there a clean way to do this?
If you do not have duplicates or that you want to delete all same elements, you can do
a.detect(&:good?)will return the firstgood?object ornilifthere is none.
a.delete(elem)will delete and return your element.Or if you have duplicates and only want to delete the first one: