[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: how to remove dups from 2 lists?

Gavin Kistner

5/11/2007 4:04:00 PM

From: Mike Steiner [mailto:mikejaysteiner@gmail.com]
> 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 )
end
}
result
end
end

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"]