From: Jeffrey Schwab Date: 2006-10-13T00:50:14+09:00 Subject: Re: Isolating non-unique items in an array Jason Burgett wrote: > I'm basically trying to the opposite of .uniq Let's say I have an array: > > ["a", "a", "a", "b", "c", "d", "d"] > > I would like to boil this down by first tossing the values that only > appear once. Which leaves me with: > > ["a", "a", "a", "d", "d"] > > Then I need to somehow determine that "a" appears 3 times and "d" > appears 2 times. Any help would be great. Thanks. # Output: # ["a", "a", "a", "d", "d"] # {"a"=>3, "d"=>2} def get_counts(keys) counts = Hash.new(0) keys.each {|k| counts[k] += 1 } counts end def non_uniq(elements) counts = get_counts(elements) counts.delete_if {|k, v| v < 2 } elements.select {|e| counts.key?(e) } end elements = ["a", "a", "a", "b", "c", "d", "d"] p non_uniq(elements) p get_counts(elements).delete_if {|k, v| v < 2 }