Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array of hashes to ONE hash in Ruby

I have an array of hashes with arrays that look something like this:

result = [
  {"id_t"=>["1"], "transcript_t"=>["I am a transcript ONE"]},
  {"id_t"=>["2"], "transcript_t"=>["I am a transcript TWO"]},
  {"id_t"=>["3"], "transcript_t"=>["I am a transcript THREE"]}
]

What I would LIKE to do, if possible, is transform it such that it becomes ONE hash where each key=>value pair is taken from the values of each hash. I don't think I'm explaining that well, so here's what I mean:

end_result = {
  "1"=>"I am a transcript ONE",
  "2"=>"I am a transcript TWO",
  "3"=>"I am a transcript THREE"
}

I've been scouring Stack Overflow and Google for various methods, but I've gotten myself confused in the process. Any ideas on how to achieve this?

like image 782
librarion Avatar asked Jan 09 '13 21:01

librarion


1 Answers

I think the key to the solution is Hash[], which will create a Hash based on an array of key/values, i.e.

Hash[[["key1", "value1"], ["key2", "value2"]]]
#=> {"key1" => "value1", "key2" => "value2"}

Just add a set of map, and you have a solution!

result = [
  {"id_t"=>["1"], "transcript_t"=>["I am a transcript ONE"]},
  {"id_t"=>["2"], "transcript_t"=>["I am a transcript TWO"]},
  {"id_t"=>["3"], "transcript_t"=>["I am a transcript THREE"]}
]
Hash[result.map(&:values).map(&:flatten)]
like image 121
Jean-Louis Giordano Avatar answered Nov 04 '22 13:11

Jean-Louis Giordano