From: Alex Young Date: 2006-10-13T00:52:19+09:00 Subject: Re: Isolating non-unique items in an array Tim Pease wrote: > On 10/12/06, 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. >> >> -- >> Posted via http://www.ruby-forum.com/. >> >> > > class Array > def count( item ) > return 0 unless self.include? item > > c = 0 > self.each {|i| c += 1 if i == item} > return c > end > end > > ary = %w(a a a b c d d) > new_ary = ary.select {|item| ary.count(item) > 1} > Better: class Array def counts # could be golfed, but clarity is king result = Hash.new{0} self.each {|a| result[a] += 1} result end end a = ["a", "a", "a", "b", "c", "d", "d"] c = a.counts a.reject{|b| c[b] == 1} # => ["a", "a", "a", "d", "d"] -- Alex