在 Ruby 中将一组散列值转换为一个散列值 [英] Converting an array of hashes to ONE hash in Ruby

查看:43
本文介绍了在 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"
}

我一直在寻找 Stack Overflow 和 Google 寻找各种方法,但在这个过程中我让自己感到困惑.关于如何实现这一目标的任何想法?

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?

推荐答案

我认为解决方案的关键是 Hash[],它将根据键/值数组创建一个 Hash,即

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

只需添加一组map,你就有了解决方案!

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

这篇关于在 Ruby 中将一组散列值转换为一个散列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆