From: Mathieu Bouchard Date: 2000-12-02T07:32:05+09:00 Subject: [ruby-talk:6723] Re: Array Intersect (&) question > >Use a hash. Here's code to do both and more. It assumes that > >each element is unique in a given array: > > @union = @intersection = @difference = (); > > %count = (); > > foreach $element (@array1, @array2) { $count{$element}++ } > > foreach $element (keys %count) { > > push @union, $element; > > push @{ $count{$element} > 1 ? \@intersection : \@difference }, > >$element > >; > > } > Wow! Much faster than the standard Ruby Array#&. Thanks much (I'll check > there myself for these sorts of questions from now on). I translated the above code into Ruby. If you run the code below, Array#& becomes quite faster than the above code. class Array; def &(other) union = [] inter = [] diff = [] count = {} (self+other).each {|x| count[x] = 1 + count.fetch(x) {0}} count.each_key {|x| union << x (count[x] > 1 ? inter : diff) << x } inter end end matju