Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active December 23, 2015 17:39
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 iwan/6670038 to your computer and use it in GitHub Desktop.
Save iwan/6670038 to your computer and use it in GitHub Desktop.
Ruby. From Array to Hash
# Given an array
arr = [1, 2, 3]
# I want to build an hash starting from an array
# like { 1 => 1, 2 => 4, 3 => 9} (where the values are the square of keys)
# long form:
hash = {}
arr.each do |e|
hash[e] = e**2
end
# compact form:
hash = Hash[arr.map{|e| [e, e**2]}]
# Pay attention to brackets!
# Hash[[1,1],[2,4],[3,9]] # <= wrong!
# Hash[[[1,1],[2,4],[3,9]]] # <= correct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment