Created
June 21, 2012 13:11
-
-
Save jcberthon/2965658 to your computer and use it in GitHub Desktop.
Return the duplicated elements of an enumerable (e.g. array) in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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