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 quicker way than doing some sort of for loop?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With