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
1 Response
That's a neat little trick, super handy for quickly mapping values, especially straight from pluck. I've also found it useful when transforming grouped data or results from joins into a quick lookup. Ruby’s implicit conversions like this make the code cleaner in places where you'd otherwise loop manually.
6 days ago ·
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#