From: Sean O'Halpin Date: 2007-10-28T22:12:18+09:00 Subject: Re: Duplicate elements in array ------=_Part_9168_18854508.1193577140330 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On 10/28/07, Shuaib Zahda wrote: > > Hello > > I am trying to output the duplicate elements in an array. I looked into > the api of ruby I found uniq method which outputs the array with no > duplication. What i want is to know which elements is duplicated. > For example > > array = ["apple", "banana", "apple", "orange"] > => ["apple", "banana", "apple", "orange"] > array.uniq > => ["apple", "banana", "orange"] > > I want the method to tell me that apple is the duplicated element > > I tried this but it does not work > > array - array.uniq > > any idea > > Regards > Shuaib > -- > Posted via http://www.ruby-forum.com/. > > Here's one way (I'm sure there must be a simpler approach - just can't think of it right now): array = ["apple", "banana", "apple", "orange"] counts = array.inject(Hash.new {|h,k| h[k] = 0 }) { |hash, item| hash[item] += 1; hash} p counts #=> {"apple"=>2, "banana"=>1, "orange"=>1} p counts.select { |k,v| v > 1 }.map{ |k, v| k}.flatten #=> ["apple"] Regards, Sean ------=_Part_9168_18854508.1193577140330--