Alex Rivera | Logout

Ruby array subtraction without removing items more than once

Asked 2010-10-04T04:03:04.627
21

The canonical Array difference example in Ruby is:

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]

What's the best way to get the following behavior instead?

[ 1, 1, 2, 2, 3, 3, 4, 5 ].subtract_once([ 1, 2, 4 ])  #=>  [ 1, 2, 3, 3, 5 ]

That is, only the first instance of each matching item in the second array is removed from the first array.

Edit
Report

1 Answer

8

This is all I can think of so far:

[1, 2, 4].each { |x| ary.delete_at ary.index(x) }
answered 2010-10-04T04:16:14.877

Your Answer