如何根据c值对此哈希进行排序?

时间:2015-11-18 02:20:01

标签: ruby-on-rails ruby sorting

h = {"Collectible\\nGames"     =>{"c"=>19},
     "Family & Friends\\nGames"=>{"c"=>71},
     "Logic Games\\n"          =>{"c"=>32},
     "Kids Games\\n"           =>{"c"=>92},
     "Classic Games\\n"        =>{"c"=>22},
     "Card Games\\n"           =>{"c"=>40},
     "Preschool\\nGames"       =>{"c"=>48}}

1 个答案:

答案 0 :(得分:2)

您的密钥是字符串("c"),而不是符号(:c)。您可以在数组上调用to_h以返回哈希值。

h.sort_by{|k, v| v["c"]}.to_h 
# => {"Collectible\nGames"=>{"c"=>19}, 
     "Classic Games\n"=>{"c"=>22}, 
     "Logic Games\n"=>{"c"=>32}, 
     "Card Games\n"=>{"c"=>40}, 
     "Preschool\nGames"=>{"c"=>48}, 
     "Family & Friends\nGames"=>{"c"=>71}, 
     "Kids Games\n"=>{"c"=>92}}