更改哈希的结构

时间:2015-04-29 13:45:11

标签: ruby-on-rails ruby hash ruby-2.0 ruby-2.2

我有如下的哈希:

{
'3.2':{
 'abc-4536':{
   "a" : "sfsdfs",
   "b" : "qweqda",
   "pa": "Printer"
    },
  'abc-2345':{
    "a": "sdfswer",
    "b": "werwewe",
    "pa": "NewsPaper"
    },
  'abc-4536':{
    "a" : "sfsdfs",
    "b" : "qweqda",
    "pa": "Printer"
    },
   ...
  }
}

所以,现在我必须像这样安排:

{
'3.2':{
  "Printer":{
    'count': 2
   },
  "NewsPaper":{
    'count': 3
   }, 
 }
}

我必须按照" pa"进行计数和分组。内部关键' 3.2'。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用以下作为示例哈希(2个“打印机”计数和1个“新闻纸张”计数):

h = {:"3.2"=>{:"abc-4536"=>{:a=>"sfsdfs", :b=>"qweqda", :pa=>"Printer"}, :"abc-2345"=>{:a=>"sdfswer", :b=>"werwewe", :pa=>"NewsPaper"}, :"abc-4537"=>{:a=>"sfsdfs", :b=>"qweqda", :pa=>"Printer"}}}

你可以这样做:

z = Array.new
h[:"3.2"].each_value {|x| z << x[:pa]}
h[:"3.2"] = Hash.new
z.each {|a| h[:"3.2"][a] = {"count": z.count {|x| x == a}}}

h现在是:

#=> {:"3.2"=>{"Printer"=>{:count=>2}, "NewsPaper"=>{:count=>1}}}