Here’s a method to delete and return all items in an Array for which
the block evaluates to true:
class Array
def delete_if!
to_delete = []
to_keep = []
each do |item|
(yield item) ? to_delete << item : to_keep << item
end
replace(to_keep)
return to_delete
end
end
Would people suggest better implementations? The obvious problem here
is that we’re duplicating arr (to_delete and to_keep contatin together
a cloned arr). I came up with an index based solution to avoid that,
but frankly it was quite ugly.
Here’s a method to delete and return all items in an Array for which
the block evaluates to true:
[…]
Would people suggest better implementations? The obvious problem here
is that we’re duplicating arr (to_delete and to_keep contatin together
a cloned arr). I came up with an index based solution to avoid that,
but frankly it was quite ugly.
$ ri Array#reject!
---------------------------------------------------------- Array#reject!
array.reject! {|item| block } → array or nil
Equivalent to +Array#delete_if+, deleting elements from _self_ for
which the block evaluates to true, but returns +nil+ if no changes
were made. Also see +Enumerable#reject+.