213, "frog"=> 128, "apple"=> 812}。 我如何重新排序以便它按降序对它们进行排序而不将其转换为数组?因此,将其更改为 {"appl-6ren">
gpt4 book ai didi

ruby - 如何在不转换为数组的情况下按 Ruby 中的数值对哈希进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 07:50:35 24 4
gpt4 key购买 nike

我有一个哈希值:{"spider"=> 213, "frog"=> 128, "apple"=> 812}

我如何重新排序以便它按降序对它们进行排序而不将其转换为数组?因此,将其更改为 {"apple"=> 812, "spider"=> 213, "frog"=> 128} 而不是将其放入数组。

我试过 .sort_by,但这会将它转换为数组。

最佳答案

在 Ruby 1.9 中,“Hashes enumerate their values in the order that the corresponding keys were inserted”,因此请确保以正确的方式插入它们:

Hash[h.sort_by { |_, v| -v }]
#=> > {"apple"=>812, "spider"=>213, "frog"=>128}

关于ruby - 如何在不转换为数组的情况下按 Ruby 中的数值对哈希进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11974927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com