From: Trans Date: 2007-08-20T05:05:34+09:00 Subject: Re: Detecting duplicates in an array, anything in the standard library ? On Aug 19, 12:34 pm, William James wrote: > On Aug 19, 5:38 am, Thibaut Barr�re wrote: > > > > > Hi! > > > Just wondering if there is something simple already built in the std > > library to remove duplicates from an array (or an enumerable). I've > > seen and used various approaches, like: > > > module Enumerable > > def dups > > inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys > > end > > end > > > which will give: > > > > %w(a b c c).dups > > > => ["c"] > > > Anything more elegant ? > > > cheers > > > Thibaut > > Here's a modification of a technique used by > Simon Kroger: > > class Array > def dups > values_at( * (0...size).to_a - uniq.map{|x| index(x)} ) > end > end > ==>nil Does everyone agree that #dups is the best name for this? I recently added this to Facets as #duplicates to avoid proximity to #dup. Is that reasonable? (Facets already had #nonuniq, btw.) T.