Last active
December 23, 2015 17:39
-
-
Save iwan/6670038 to your computer and use it in GitHub Desktop.
Ruby. From Array to Hash
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
# 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