Skip to content

Instantly share code, notes, and snippets.

@shinokada
Created May 2, 2014 21:52
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 shinokada/11487116 to your computer and use it in GitHub Desktop.
Save shinokada/11487116 to your computer and use it in GitHub Desktop.
# Ruby: How to find and return a duplicate value in array?
ary = ["A", "B", "C", "B", "A"]
ary.group_by { |e| e }.select { |k, v| v.size > 1 }.map(&:first) # => ["A", "B"]
ary.sort.chunk { |e| e }.select { |e, count| count.size > 1 }.map(&:first)
ary.select { |e| ary.count(e) > 1 }.uniq # => ["A", "B"]
ary.detect{ |e| ary.count(e) > 1 } # => "A", `detect` return only the first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment