From: Sam Duncan Date: 2012-04-20T07:58:26+09:00 Subject: Re: finding duplicates in an array and its index number On 20/04/12 09:53, newto ruby wrote: > Hi, > > I have following array and I am trying to find if there are duplicates > in the array. I also want to find out their index. > > e.g. > > a=[1,2,3,1,3] > > Here 1 is a duplicate which comes twice and its index is 0 and 3 in the > array. > > Any suggestions? > > Thanks > How about; 1.9.3p125 :001 > foo = [1,2,3,1,3] => [1, 2, 3, 1, 3] 1.9.3p125 :002 > dup_indices = Hash.new {|h,k| h[k]=[]} => {} 1.9.3p125 :003 > foo.each_index {|i| dup_indices[foo[i]] << i unless 1 == foo.count(foo[i])} => [1, 2, 3, 1, 3] 1.9.3p125 :004 > dup_indices => {1=>[0, 3], 3=>[2, 4]} Sam