Skip to content

Instantly share code, notes, and snippets.

@jcberthon
Created June 21, 2012 13:11
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 jcberthon/2965658 to your computer and use it in GitHub Desktop.
Save jcberthon/2965658 to your computer and use it in GitHub Desktop.
Return the duplicated elements of an enumerable (e.g. array) in Ruby
# Source: http://www.dzone.com/snippets/identify-duplicates-array
module Enumerable
# Returns any duplicates entry if found
# Usage: <enumerable>.report_duplicate
def report_duplicate
inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
end
end
# Example call:
# an_array = [1,3,5,5,6,7,9,10,14,18,22,22,4,4,4,3,6,13,22,14]
# puts an_array.dups.inspect
# => [3, 5, 6, 7, 14, 22, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment