运维开发网

ruby – 从散列值排序的哈希中获取键数组

运维开发网 https://www.qedev.com 2020-07-27 22:46 出处:网络 作者:运维开发网整理
我有一个像这样的哈希 {"red" => 3, "blue" => 1, "yellow" => 3, "green" => 1, "black" => 4} 我想按照散列值的顺序排序并显示前三种颜色,即 ["black", "red", "yellow"] 我试着做一些像sort_by {| x,y | h [x]< => h [y]}和max_by {| x,y | h [x]},但我只得到[
我有一个像这样的哈希

{"red" => 3, "blue" => 1, "yellow" => 3, "green" => 1, "black" => 4}

我想按照散列值的顺序排序并显示前三种颜色,即

["black", "red", "yellow"]

我试着做一些像sort_by {| x,y | h [x]< => h [y]}和max_by {| x,y | h [x]},但我只得到[“黑色”].你如何获得前三名?

作为变体:

h = {"green"=>1, "red"=>3, "yellow"=>3, "blue"=>1, "black"=>4}
h.sort_by{ |color, n| -n }.map(&:first).take(3) #=> ["black", "red", "yellow"]
0

精彩评论

暂无评论...
验证码 换一张
取 消