在 Ruby 中按哈希值降序排序 [英] Descending sort by value of a Hash in Ruby

查看:18
本文介绍了在 Ruby 中按哈希值降序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入哈希:h = { "a" =>20,b"=>30,c"=>10 }

升序:h.sort {|a,b|a[1]<=>b[1]}#=>[["c", 10], ["a", 20], ["b", 30]]

但是,我需要 [["b", 30], ["a", 20], ["c", 10]]

我们怎样才能让它反过来工作,<=> 是什么意思?

How is can we make it work the other way around, what does <=> mean?

推荐答案

您可以一次更干净、更清晰、更快速地完成!像这样:

You can have it cleaner, clearer and faster, all at once! Like this:

h.sort_by {|k,v| v}.reverse

我对具有随机值的 1000 个元素的散列进行排序的 3000 次迭代进行了基准测试,并得到了这些时间:

I benchmarked timings on 3000 iterations of sorting a 1000-element hash with random values, and got these times:

h.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s
h.sort {|x,y| y[1] <=> x[1]} -- 12.3s
h.sort_by {|k,v| -v} -- 5.9s
h.sort_by {|k,v| v}.reverse -- 3.7

这篇关于在 Ruby 中按哈希值降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆