From: "Jesús Gabriel y Galán" Date: 2009-01-15T21:21:58+09:00 Subject: Re: Returning a duplicate from an Array On Thu, Jan 15, 2009 at 12:18 PM, Jimmy Kofler wrote: > > class Array > def dups > uniq.select{ |e| (self-[e]).size < self.size - 1 } > end > end > > p [ 1, 1, 2, 2, 3, 3, 4, 5 ].dups #=> [1, 2, 3] Regarding this and other solutions: the OP accepted a solution from Andy Cooper which return *all* duplicates. I mean, if a number appears three times, it will appear two in the solution, and not one: irb(main):001:0> a = [1,1,1,1,2,2,3,4,5,5,5] => [1, 1, 1, 1, 2, 2, 3, 4, 5, 5, 5] irb(main):008:0> class Array irb(main):009:1> def dups irb(main):010:2> uniq.select{ |e| (self-[e]).size < self.size - 1 } irb(main):011:2> end irb(main):012:1> end => nil irb(main):013:0> a.dups => [1, 2, 5] Should be [1,1,1,2,3,4,5,5]. If order is not important: irb(main):014:0> class Array irb(main):015:1> def dups irb(main):016:2> h = Hash.new 0 irb(main):017:2> each {|x| h[x] += 1} irb(main):018:2> h.inject([]) {|res, (k,v)| res << ([k] * (v-1)) if v > 1; res.flatten} irb(main):019:2> end irb(main):020:1> end => nil irb(main):021:0> a.dups => [5, 5, 1, 1, 1, 2] Jesus.