Last Updated: August 27, 2022
·
2.058K
· hunterae

Ruby - Instantiate Hash from Array

Today I learned: you can build Hashes directly with an Array of Arrays, where the inner arrays consists of 2 elements:

Build Hashes directly with an Array of Arrays

a = [[:a, 1], [:b, 2], [:c, 3]]
hash = Hash[a]
# returns { a: 1, b: 2, c: 3 }
This can be further used in combination with a database query:
Hash[CampaignsKeyword.limit(10).pluck(:id, :keyword_id)]
# => {1=>1, 2=>2, 3=>3, 160=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9}