From: "David A. Black" Date: 2007-08-19T22:06:54+09:00 Subject: Re: Detecting duplicates in an array, anything in the standard library ? --1926193751-1394418063-1187528815=:15936 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1394418063-1187528815=:15936" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1394418063-1187528815=:15936 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Sun, 19 Aug 2007, Ari Brown wrote: > > On Aug 19, 2007, at 6:39 AM, Thibaut Barr=E8re wrote: > >> Hi! >>=20 >> 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: >>=20 >> module Enumerable >> def dups >> inject({}) {|h,v| h[v]=3Dh[v].to_i+1; h}.reject{|k,v| v=3D=3D1}.keys >> end >> end >>=20 >> which will give: >>=20 >>> %w(a b c c).dups >> =3D> ["c"] >>=20 >> Anything more elegant ? > > Couldn't you also just do a union with itself? > > a =3D %w(a b c b a) > b =3D a & a #=3D> ["a", "b", "c"] > > Score one for me :-)) I think that just reinvents uniq (see my previous reinvention :-) For what it's worth, here's a nice-looking but probably very inefficient version: module ArrayStuff def count(e) select {|f| f =3D=3D e }.size end def dups select {|e| count(e) > 1 }.uniq end end a =3D [1,2,3,3,4,5,2].extend(ArrayStuff) p a.dups # [2,3] David --=20 * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com) --1926193751-1394418063-1187528815=:15936-- --1926193751-1394418063-1187528815=:15936--