How can I convert an array of rubies hashes into one hash?
If I start with an array of hashes like this:
[{"name"=>"apple", "value"=>"red"},
{"name"=>"banana", "value"=>"yellow"},
{"name"=>"grape", "value"=>"purple"}]
How can I turn it into this single hash:
{apple: "red", banana: "yellow", grape: "purple"}
Is there a faster way than doing some sort of for loop?
+3
source to share
2 answers
arr = [{"name"=>"apple", "value"=>"red"},
{"name"=>"banana", "value"=>"yellow"},
{"name"=>"grape", "value"=>"purple"}]
Hash[arr.map { |h| [h["name"].to_sym , h["value"]] }]
#=> {:apple=>"red", :banana=>"yellow", :grape=>"purple"}
With Ruby 2.1+
arr.map { |h| [h["name"].to_sym , h["value"]] }.to_h
#=> {:apple=>"red", :banana=>"yellow", :grape=>"purple"}
+6
source to share
Create a hash from a split array
If you don't really need your keys to be symbols, this will work:
fruits = [{"name"=>"apple", "value"=>"red"},
{"name"=>"banana", "value"=>"yellow"},
{"name"=>"grape", "value"=>"purple"}]
Hash[*fruits.flat_map(&:values)]
#=> {"apple"=>"red", "banana"=>"yellow", "grape"=>"purple"}
Indifferent access
If you just want to access the elements with symbols rather than strings, and you don't care if the keys will actually be stored as strings, then you can require a little "ActiveSupport Effect" part and use HashWithIndifferentAccess :
require 'active_support/core_ext/hash/indifferent_access'
fruits = [{"name"=>"apple", "value"=>"red"},
{"name"=>"banana", "value"=>"yellow"},
{"name"=>"grape", "value"=>"purple"}]
h = HashWithIndifferentAccess[*fruits.flat_map(&:values)]
h[:apple]
#=> "red"
0
source to share