From: Robert Klemme Date: 2005-10-16T04:31:55+09:00 Subject: Re: How to get non-unique elements from an array? Sam Kong wrote: >> You don't need the exact number of repetitions. Try this: >> a = [0,1,2,3,4,5,2,3] >> h = {} >> u = a.inject([]) {|res, x| h[x] ? res + [x] : h[x] = res} > > Thank you for the insight. > > However, your code doesn't work if an element repeats more than twice. > > a = [0,1,2,3,4,5,2,3,2] #there are three 2's. > Your code's result is [2, 3, 2] instead of [2, 3] > It should be modified like > u = a.inject([]) {|res, x| h[x] ? res + [x] : h[x] = res}.uniq > > Other than that, I like your way. > Thank you again. > > Sam >> a = [0,1,2,3,4,5,2,3] => [0, 1, 2, 3, 4, 5, 2, 3] >> a.inject(Hash.new(0)) {|h,e| h[e]+=1;h}.select {|k,v|v>1}.map {|a,b|a} => [2, 3] Quite complicated... robert