按从高到低的值对哈希数组进行排序

时间:2018-04-03 09:33:07

标签: arrays ruby sorting hash

我有这种格式的哈希:

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

我四处寻找解决方案,但没有发现任何与此问题陈述相符的内容。

请建议!

2 个答案:

答案 0 :(得分:4)

应该是

images_found["results"] = images_found["results"].sort_by(&:values).reverse

答案 1 :(得分:4)

有多种方法可以获得所需的结果:

images_found["results"].sort_by! { |x| x.values.first }.reverse!

请注意,使用!的方法会更改原始哈希值。如果您不想更改原始哈希,请删除!

另一种选择是使用-符号进行排序:

images_found["results"].sort_by! { |x| - x.values.first }