Forum: Ruby Re: how to remove dups from 2 lists?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
825738339f48c5b8b2a72c02caf3d91c?d=identicon&s=25 Gavin Kistner (Guest)
on 2007-05-11 18:04
(Received via mailing list)
From: Mike Steiner []
> I'm looking for a function that will eliminate all matching
> items, like canceling terms in a fraction. If the first list
> has 3 "a"s, and the second list has 5 "a"s, then afterwards
> the first list should have 0 "a"s and the second list should
> have 2 "a"s.

class Array
  def remove_instances( *values )
    result = dup
    values.flatten.each{ |value|
      if i = result.index( value )
        result.delete_at( i )

a1 = %w| a a a b b c |
a2 = %w| a a a a a b |

p a1.remove_instances( a2 )
#=> ["b", "c"]
p a2.remove_instances( a1 )
#=> ["a", "a"]
This topic is locked and can not be replied to.