Converting an array of hashes to ONE hash in Ruby

前端 未结 2 918
我在风中等你
我在风中等你 2020-12-31 22:20

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

result = [
  {\"id_t\"=>[\"1\"], \"transcript_t\"=>[\"I am a transcript ONE\"]},
          


        
相关标签:
2条回答
  • 2020-12-31 22:43

    Try this

    result.inject({}){|acc, hash| acc[hash.values[0][0]] = hash.values[1][0]; acc }
    
    => { "1"=>"I am a transcript ONE", 
         "2"=>"I am a transcript TWO",
         "3"=>"I am a transcript THREE" } 
    
    0 讨论(0)
  • 2020-12-31 22:53

    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)]
    
    0 讨论(0)
提交回复
热议问题