From: "pauldacus@..." Date: 2005-10-18T01:03:06+09:00 Subject: Re: How to get non-unique elements from an array? Young grasshoppers... let us never forget the power of the REGEX! Let us not bother with counters or blocks... let us GSUB this bad boy! a = [0,1,2,3,4,5,2,3] a.sort.to_s.gsub(/(.)(\1)+/, '').split(//) =>["0", "1", "4", "5"] Sure... it returns the elements as strings, but a quick "to_i" call in the inevitable iterator that is coming solves that. This thing is also subject to a Schwartzian Transform of the "map-sort-map" type. Paul Dacus Sam Kong wrote: > Hello! > > I need to get non-unique elements from an array. > The best I came up with was using a hash as a counter for each unique > elements. > > a = [0,1,2,3,4,5,2,3] > > #What I want to get is [2,3] as 2,3 are non-unique elements. > > h = {} > a.each do |i| > if h[i] > h[i] += 1 > else > h[i] = 1 > end > end > > u = [] > h.each do |k, v| > if v > 1 > u << k > end > end > > #now u == [2,3] > > This works fine. > But I think there's a better way. > How do you handle such a case? > > Thanks in advance. > > Sam