Skip to content

Instantly share code, notes, and snippets.

@wrburgess
Created January 30, 2014 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrburgess/8718091 to your computer and use it in GitHub Desktop.
Save wrburgess/8718091 to your computer and use it in GitHub Desktop.
Finding duplicate items in an array #ruby
arr = [ 1, 2, 3, 2, 4, 5, 3]
My favourite way of counting elements is:
counts = arr.group_by{|i| i}.map{|k,v| [k, v.count] }
# => [[1, 1], [2, 2], [3, 2], [4, 1], [5, 1]]
If you need a hash instead of an array:
Hash[*counts.flatten]
# => {1=>1, 2=>2, 3=>2, 4=>1, 5=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment