From: Wilson Bilkovich Date: 2006-10-28T02:57:06+09:00 Subject: Re: how to get only the duplicatet items from an array On 10/27/06, Nico Landgraf wrote: > hi all, > > is there a oneline to get only the duplicatet item from an array? > > i have an array like this > aTemp = [1, 1, 2, 2, 3, 4] > and i want to know, which items are duplicatet. > > i thought i can do it like > aTemp - aTemp.uniq > > [1, 1, 2, 2, 3, 4] - [1, 2, 3, 4] => [1, 2] > like inside the manual > > but i get only an empty array > > > so i found an bad solution and hope you can help me to get the right way. > Here's one way: irb(main):001:0> h = Hash.new(0) => {} irb(main):002:0> array = [1,1,2,2,3,4,1] => [1, 1, 2, 2, 3, 4, 1] irb(main):003:0> duplicates = array.select {|e| h[e] += 1; h[e] == 1} => [1, 2, 3, 4] irb(main):004:0> There are shorter ways, but I find that one to be pretty readable. The resulting array doesn't contain duplicates, just one each of the entries that appeared multiple times in the input array. It also makes it easy to find out how many times something appeared, if you need that. h[1] will return 3, for example.