1

我有一个像下面这样的哈希:

{
'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
   }, 
 }
}

我必须按“3.2”内的“pa”键进行计数和分组。有任何想法吗 ?

4

3 回答 3

0

Assuming that you have an array of specified objects:

array.map{ |x| { x.first[0] => x.first[1].map { |k,v| [v['pa'], "calculated value"] }.to_h } }

or if you have one hash:

{ hash.first[0] => hash.first[1].map { |k,v| [v['pa'], "calculated value"] }.to_h } 
于 2015-04-29T14:09:06.103 回答
0

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

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}}}
于 2015-04-30T05:37:40.600 回答
-1

假设您将我们真正使用的散列转储到一个变量中,只是为了演示。我将把您在上面写出的哈希称为“old_hash”。

修改

现在反映您对“计数”的需求。

    # Isolate the part with which we're working. If you had multiple
    #   version (like 3.1, 3.0) just perform this on .each of them.
    x = old_hash['3.2']

    # Initialize a counter
    counter = 0

    # Iterate through every level in '3.2'
    x.each do |k, v|

      # Increment the counter
      counter += 1

      # Create a new key-value pair in x, where the key is the "pa"
      #   value of hash currently selected by this loop, and assign
      #   it a count
      x[ x[k]['pa'] ] = { count: counter }

      # Remove the hash currently selected by your loop from x
      #  (if you're using its other values for a calulation, make
      #   sure you do that first)
      x.delete( k )
    end

    # Rewrite your old "3.2" into the new hash
    old_hash['3.2'] = x

有很多更优雅的方法可以做到这一点,但这至少应该是一个易于理解的过程,如果你有复杂的计算要执行,现在你有很大的可读性空间。

于 2015-04-29T15:26:52.947 回答