我有一个这种格式的散列:
images_found = {
"results" => [
{"img_1"=>1.923076923076923},
{"img_2"=>0.8241758241758242},
{"img_3"=>0.6868131868131868},
{"img_4"=>0.5494505494505495},
{"img_5"=>0.4120879120879121},
{"img_6"=>0.3434065934065934},
{"img_7"=>0.2747252747252747},
{"img_8"=>0.2060439560439561},
{"img_9"=>0.1373626373626374},
{"img_10"=>0.06868131868131869},
{"img_11"=>0.5494505494505495},
{"img_12"=>0.3434065934065934},
{"img_13"=>0.2747252747252747},
{"img_14"=>0.2060439560439561},
{"img_15"=>0.1373626373626374},
{"img_16"=>0.06868131868131869}
],
"type" => "SEARCH_RESULTS"
}
我想按值从高到低对
images_found["results"]
进行排序,结果是:images_found = {
"results"=> [
{"img_1"=>1.923076923076923},
{"img_2"=>0.8241758241758242},
{"img_3"=>0.6868131868131868},
{"img_4"=>0.5494505494505495},
{"img_11"=>0.5494505494505495},
{"img_5"=>0.4120879120879121},
{"img_6"=>0.3434065934065934},
{"img_12"=>0.3434065934065934},
{"img_7"=>0.2747252747252747},
{"img_13"=>0.2747252747252747},
{"img_8"=>0.2060439560439561},
{"img_14"=>0.2060439560439561},
{"img_9"=>0.1373626373626374},
{"img_15"=>0.1373626373626374},
{"img_10"=>0.06868131868131869},
{"img_16"=>0.06868131868131869}
],
"type" => "SEARCH_RESULTS"
}
我尝试的解决方案是
images_found["results"].sort_by! {|_key, value| value}
但它不起作用。当我试图调试
value
时,它正在打印nil
我四处寻找解决方案,但没有找到与此问题陈述相匹配的任何内容。
请建议!
最佳答案
应该是
images_found["results"] = images_found["results"].sort_by(&:values).reverse
关于arrays - 按值从高到低对哈希数组排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49626713/