Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a ruby array of hashes into a single 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 quicker way than doing some sort of for loop?

like image 215
David Mckee Avatar asked Feb 12 '23 17:02

David Mckee


1 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"}
like image 115
Cary Swoveland Avatar answered Apr 08 '23 11:04

Cary Swoveland