Created
November 7, 2015 16:30
-
-
Save worldofprasanna/1dd1cfaa500d3d5fd142 to your computer and use it in GitHub Desktop.
Snippet to convert Array to Hash with duplicate elements combined together
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
def array_to_hash(arr) | |
hash_val = Hash.new | |
arr.uniq.each {|n| hash_val[n] = arr.grep(n)} | |
hash_val | |
end | |
# array_to_hash([1,2,3,2,1]) => {1=>[1, 1], 2=>[2, 2], 3=>[3]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment