Gavin Kistner
10/12/2006 7:55:00 PM
> From: Phrogz [mailto:gavin@refinery.com]
> class Array
> def duplicates_count
> uniq.map{ |e|
> if ( count = grep(e).size ) > 1
> { e => count }
> end
> }.compact
> end
> end
>
> a = ["a", "a", "a", "b", "c", "d", "d"]
> p a.duplicates_count
> #=> [{"a"=>3}, {"d"=>2}]
Don't listen to that Phrogz character, he's insane!
More like:
class Array
def duplicates_count
Hash[ *uniq.map{ |e|
if ( count = grep(e).size ) > 1
[e, count]
end
}.compact.flatten ]
end
end
a = ["a", "a", "a", "b", "c", "d", "d"]
p a.duplicates_count
#=> {"a"=>3, "d"=>2}
But of course, other posts in this thread are likely faster.