重组哈希

时间:2015-05-03 22:22:19

标签: ruby-on-rails ruby hash

我有一个初始哈希,其结构如下所示

初始哈希

initial_hash = {
 `section1`:{
  'person_name1':{
     'city': 'City1',
     'country': 'Country1'
   },
  'person_name2':{
     'city': 'City2',
     'country': 'Country2'
   },
   ...
 },
 `section2`:{
  'person_name12':{
     'city': 'City12',
     'country': 'Country12'
   },
  'person_name23':{
     'city': 'City23',
     'country': 'Country23'
   },
   ...
 }
}

最终哈希

final_hash = {
  `section1`:{
   'country1':{
      'city': 'City1',
      'person_name': 'person_name1'
    },
   'country2':{
      'city': 'City2',
      'person_name': 'person_name2'
    },
    ...
  },
  `section2:{
   'country12':{
      'city': 'City12',
      'person_name': 'person_name12'
    },
   'country23':{
      'city': 'City23',
      'person_name': 'person_name23'
    },
    ...
  }
}

正如您所看到的那样,final_hash已经过重组,因此countryperson_name取代了彼此。到目前为止,我的尝试如下:

我的尝试:

final_hash = {}
initial_hash.each do |h|
 final_hash[h[0]] = {}
 final_hash[h[0]] = h[1].group_by{|x| x[1]['country']}.each{|_, v| v.map!{|h| h[1]}}
end

上述尝试有助于我获得这种结构:

final_hash = {
  'section1':{
    'country'1: {
      'city': 'City1',
      'country': 'Country1'
     },
     'country2': {
      'city': 'City2',
      'country': 'Country2'
     },
    ...
  },
 'section2':{
    'country'12: {
      'city': 'City12',
      'country': 'Country12'
     },
     'country23': {
      'city': 'City23',
      'country': 'Country23'
     },
    ...
  } 
}

我无法理解如何放置person_name代替country。我尝试将each加到map!块的结果中。但到目前为止没有运气。要添加到此问题,我有一个json data which consist of 1000 records,所以performance is a concern here

提前致谢

1 个答案:

答案 0 :(得分:1)

尝试使用inject:

1)只注入内部哈希:

initial_hash.inject({}){ |h,(section,inner_hash)| h.merge section => inner_hash.inject({}) { |inner_h,(k,v)| inner_h.merge v.delete(:country) => v.merge(person_name: k) }}

2)使用map&注入:

Hash[initial_hash.map { |section, inner_hash| [section, inner_hash.inject({}) { |inner_h, (k, v)| inner_h.merge v.delete(:country) => v.merge(person_name: k) }]}]

基准(1000):

                user     system      total        real

  injects:    0.060000   0.010000   0.070000 (  0.057551)

  map&inject: 0.060000   0.000000   0.060000 (  0.053678)