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}
Written by Andrew Hunter
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#