对散列哈希进行排序

时间:2012-01-21 03:12:32

标签: ruby sorting hash

我有一个散列,其中包含许多需要按其最深值排序的键/值。

这是我正在处理的一个例子:

hash = {"en"=> 
    { "key1"=> 
        {"foo1"=>1, 
         "foo2"=>2, 
         "foo3"=>1}, 
      "key2"=>
        {"foo4"=>1,
         "foo5"=>3, 
         "foo6"=>2, 
         "foo7"=>1}
    }
 "fr"=>
    ....
}

我想要键入每个主键(即“en”,“fr”,es“)并按键内的值排序。因此,”en“和”key1“在其中具有”value2“最高编号(频率)的顶部。然后对其余的哈希做同样的事情。我不会对键“en”,“fr”等的顺序感到困扰。

所以我希望输出是这样的:

hash = {"en"=> 
    { "key1"=> 
        {"foo2"=>2, 
         "foo1"=>1, 
         "foo3"=>1}, 
      "key2"=>
        {"foo5"=>3,
         "foo6"=>2, 
         "foo4"=>1, 
         "foo7"=>1}
    }
 "fr"=>
    ....
}

1 个答案:

答案 0 :(得分:2)

脆弱,但应该有效:

def sort_deep(h)
  if h.values.all?{ |o| o.is_a? Numeric }
    Hash[ h.sort_by{|k,v|[-v,k]} ]
  else
    Hash[ h.map{ |k,v| [ k, sort_deep(v) ] } ]
  end
end

证明:

hash = {"en"=> 
    { "key1"=> 
        {"foo1"=>1, 
         "foo2"=>2, 
         "foo3"=>1}, 
      "key2"=>
        {"foo4"=>1,
         "foo5"=>3, 
         "foo6"=>2, 
         "foo7"=>1}
    },
 "fr"=>
    { "key1"=> 
        {"foo1"=>91, 
         "foo2"=>22, 
         "foo3"=>12}, 
      "key2"=>
        {"foo4"=>21,
         "foo5"=>31, 
         "foo6"=>27, 
         "foo7"=>11}
    }
}
require 'pp'
pp sort_deep(hash)
#=> {"en"=>
#=>   {"key1"=>{"foo2"=>2, "foo1"=>1, "foo3"=>1},
#=>    "key2"=>{"foo5"=>3, "foo6"=>2, "foo4"=>1, "foo7"=>1}},
#=>  "fr"=>
#=>   {"key1"=>{"foo1"=>91, "foo2"=>22, "foo3"=>12},
#=>    "key2"=>{"foo5"=>31, "foo6"=>27, "foo4"=>21, "foo7"=>11}}}