Delete from Array and return deleted elements in Ruby Delete from Array and return deleted elements in Ruby arrays arrays

Delete from Array and return deleted elements in Ruby


If you don't need to retain the object id of a:

a = [1,2,3,4,5,6,7,8,9,10]b, a = a.partition{|e| e < 4}b # => [1, 2, 3]a # => [4, 5, 6, 7, 8, 9, 10]

If you do need to retain the object id of a, then use a temporal array c:

a = [1,2,3,4,5,6,7,8,9,10]b, c = a.partition{|e| e < 4}a.replace(c)


Rails 6 now has this:

a = [1, 2, 3]#=> [1, 2, 3]a.extract! { |n| n.even? }#=> [2]a#=> [1, 3] 


If you were only deleting one item, this doesn't require duplicating the array, etc:

array = [{ id: 1 }, { id: 2 }, {id: 3 }]array.delete_at(array.find_index { |element| element[:id] == 1 })#=> {:id=>1}