Sunday, May 2, 2010

Find duplicates in an Array with grep

The following example finds duplicates in an array by selecting all array items which have apear more than once.
a = %w(a b a c)
a.uniq.select {|x| a.grep(x).length > 1}
#=> ["a"]

a = %w(a b a c d d d e f g h f)
a.uniq.select {|x| a.grep(x).length > 1}
#=> ["a", "d", "f"]
 
a = %w(a b a c d d d e f g h f)
a.group_by(&:to_s).select{|k,v| v.length > 1}
#=> {"a"=>["a", "a"], "d"=>["d", "d", "d"], "f"=>["f", "f"]}
http://snippets.dzone.com/posts/show/11219

No comments: