创建嵌套哈希

时间:2015-10-02 15:00:30

标签: arrays ruby hash nested

我有一个这样的数组:

[
  {:game_id=>546012, :period=>:fg, :stat_name=>:hits, :result=>12, :team_id=>1104}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:errors, :result=>1, :team_id=>1104}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:hits, :result=>9, :team_id=>1103}, 
  {:game_id=>546012, :period=>:fg, :stat_name=>:errors, :result=>3, :team_id=>1103}
]

如何将其变成这样的项目数组:

{ 546012 => { :hits => { :fg => { 1104 => 12,  
                                  1103 => 9 } } 
              :errors => { :fg => { 1104 => 1,
                                  1103 => 3 } } }

2 个答案:

答案 0 :(得分:2)

首先,创建一个由:game_id

组织的哈希
{ 546012 => {{
  {:period=>:fg, :stat_name=>:hits, :result=>12, :team_id=>1104},
  {:period=>:fg, :stat_name=>:errors, :result=>1, :team_id=>1104},
  {:period=>:fg, :stat_name=>:hits, :result=>9, :team_id=>1103},
  {:period=>:fg, :stat_name=>:errors, :result=>3, :team_id=>1103}
]}

然后分组:stat_name

{ 546012 => [
  {:hits => [
     {:period=>:fg, :result=>12, :team_id=>1104},
     {:period=>:fg, :result=>9, :team_id=>1103}],
   :errors => [
     {:period=>:fg, :result=>1, :team_id=>1104},
     {:period=>:fg, :result=>3, :team_id=>1103}
   ]}
]}

然后分组:

{ 546012 => [
  {:hits => [
     :fg => [{:result=>12, :team_id=>1104},
       {:result=>9, :team_id=>1103}]
     ]}
   ]},
   :errors => [
     :fg => [{:result=>1, :team_id=>1104},
       {:result=>3, :team_id=>1103}]
   ]}
]}

最后,group by:team_id并将每个人与其结果相关联:

{ 546012 => [
  {:hits => [
     :fg => [1104 => 12, 1103 => 9]
   ]},
   :errors => [
     :fg => [1104 => 1, 1103 => 3]
   ]}
]}

至于如何创建这些分组,我会把它作为练习留给你。

一种可能的方法是遍历每个项目并创建存储这些新映射的对象的新副本。例如,如果我们有这个对象:

foods = {
  {:food => lemon, :taste => sour},
  {:food => pretzel, :taste => salty},
  {:food => pretzel, :taste => sweet}
}

我们可以像(伪代码)这样​​的食物分组:

newfoods = {};
foreach item in foods:
   newfoods[ item.food ].push( item.taste );

结束

newfoods = [
  { lemon => [sour] },
  { pretzel => [sweet, salty] }
]

答案 1 :(得分:1)

您可以做的最佳选择是flatten

积分转到this question