Skip to content

Instantly share code, notes, and snippets.

@worldofprasanna
Created November 7, 2015 16:30
Show Gist options
  • Save worldofprasanna/1dd1cfaa500d3d5fd142 to your computer and use it in GitHub Desktop.
Save worldofprasanna/1dd1cfaa500d3d5fd142 to your computer and use it in GitHub Desktop.
Snippet to convert Array to Hash with duplicate elements combined together
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