From: Ryan Leavengood Date: 2005-10-18T05:11:41+09:00 Subject: Re: How to get non-unique elements from an array? On 10/17/05, Sam Kong wrote: > > I wonder if my slightly modified version works. It works, but is considerably slower (I've included a few other recent submissions as well): require 'benchmark' include Benchmark a = [0,1,2,3,4,5,2,3] BMN = 50000 bm(5) do |bx| bx.report('index ') { BMN.times { a.select{|e| a.index(e) != a.rindex(e)}.uniq } } bx.report('grep ') { BMN.times { a.select{|e| a.grep(e).length > 1}.uniq } } bx.report('scan ') { BMN.times { a.sort.join(' ').to_s.scan(/(\d+)\s(\1)+/).flatten.uniq } } bx.report('inject') { BMN.times { a.uniq.inject(a.dup) { |b,i| b.delete_at(b.index(i)) ; b } } } bx.report('gsub ') { BMN.times { a.to_s.gsub(/(.)(?!.*\1)/,'').split('').map{|i|i.to_i} } } end Results on my laptop: user system total real index 1.281000 0.000000 1.281000 ( 1.281000) grep 3.813000 0.015000 3.828000 ( 3.827000) scan 3.515000 0.000000 3.515000 ( 3.531000) inject 1.594000 0.000000 1.594000 ( 1.593000) gsub 3.063000 0.016000 3.079000 ( 3.078000) Whoever created that index and rindex based solution created a very fast one. I'll leave it as an exercise for the reading to benchmark all the other solutions. Ryan