From: Harry Kakueki Date: 2007-05-11T23:41:29+09:00 Subject: Re: how to remove dups from 2 lists? On 5/11/07, Mike Steiner wrote: > I'm trying to write some code that removes all elements from 2 lists that > are in both lists. However, I don't want any duplicates from each list > deleted also (which is what the array "-" operator does). The code I have > now doesn't handle restarting the current iteration for both loops when a > match is found and deleted in both loops. Here's the code: > > def RemoveDupsFromLists ( list1 , list2 ) > list1.each_index do | i | > list2.each_index do | j | > if list1[i] == list2[j] > list1.delete_at ( i ) > list2.delete_at ( j ) > end > end > end > return [ list1 , list2 ] > end > > What's weird is that doing this is easy in C (my first language), but > difficult in Ruby. Everything else I've seen has been MUCH easier in Ruby. > > Mike Steiner > After thinking about your question again, I think you meant something a little different than what I was thinking before, I think :) :) This is no shorter than your code, just different. arr1 = %w[a b car car b c r c car c c r d] arr2 = %w[a r1 a b c c car d r r r d] counts1 = Hash.new(0) arr1.each {|x| counts1[x] += 1} counts2 = Hash.new(0) arr2.each {|x| counts2[x] += 1} new1 = [] new2 = [] arr1.uniq.each do |x| (counts1[x] - counts2[x]).times {new1 << x} if counts1[x] > counts2[x] end arr2.uniq.each do |x| (counts2[x] - counts1[x]).times {new2 << x} if counts2[x] > counts1[x] end p new1 #["b","car","car", "c", "c"] p new2 #["a","r1","d","r"] Harry -- http://www.kakueki.com/ruby/list.html A Look into Japanese Ruby List in English