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

查看:87
本文介绍了在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

我在3000次迭代中对基于1000个元素的散列进行基准测试,并得到这些时间:

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天全站免登陆