From: Ryan Davis Date: 2012-04-21T08:47:41+09:00 Subject: Re: finding duplicates in an array and its index number On Apr 20, 2012, at 03:46 , Lars Haugseth wrote: > On 04/19/2012 11:53 PM, 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. > > Generate a hash with unique items as keys, and arrays of indices as values, > then select only those with more than one index: > > array = [1, 2, 3, 4, 5, 3, 6, 7, 2, 8, 1, 9] > > array.each_with_index.reduce({}) { |hash, (item, index)| > hash[item] = (hash[item] || []) << index > hash > }.select { |key, value| > value.size > 1 > } > > # => {1=>[0, 10], 2=>[1, 8], 3=>[2, 5]} Don't use reduce/inject for non-reductive applications. Use something more appropriate, like a plain each. Also use Hash to its full capabilities: hash = Hash.new { |h,k| h[k] = [] } then it is as clean as: array.each_with_index do |val, idx| hash[val] << idx end Notice how you're not constantly re-assigning hash for no good reason in my version? That adds up, but more importantly it obfuscates the original intent.