简体   繁体   English

将哈希数组转换为 Ruby 中的一个 hash

[英]Converting an array of hashes to ONE hash in Ruby

I have an array of hashes with arrays that look something like this:我有一个 arrays 的哈希数组,看起来像这样:

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:如果可能的话,我想做的是将其转换为 ONE hash,其中每个键=>值对都取自每个 hash 的值。我认为我没有很好地解释,所以这就是我是说:

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.我一直在 Stack Overflow 和 Google 上搜索各种方法,但在这个过程中我感到很困惑。 Any ideas on how to achieve this?关于如何实现这一目标的任何想法?

I think the key to the solution is Hash[] , which will create a Hash based on an array of key/values, ie 我认为解决方案的关键是Hash[] ,它将根据键/值数组创建一个Hash,即

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

Just add a set of map , and you have a solution! 只需添加一组map ,您就有了解决方案!

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)]

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" } 

Another possibility is using a combo of Enumerable#inject and Hash#merge :另一种可能性是使用Enumerable#injectHash#merge的组合:

result.inject({}) do |acc, hash|
   acc.merge({hash['id_t'].first => hash['transcript_t'].first})
end
=> { "1"=>"I am a transcript ONE",
     "2"=>"I am a transcript TWO",
     "3"=>"I am a transcript THREE" }

This minimizes the need for [] -constructions, and the additional explicit return appendix of ; acc这最大限度地减少了对[]结构的需要,以及 ; 的额外显式返回附录; acc ; acc . ; acc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM