根据值对红宝石中的哈希进行排序,然后对密钥进行排序 [英] Sorting a hash in ruby based on value and then key

查看:94
本文介绍了根据值对红宝石中的哈希进行排序,然后对密钥进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据值和键对红宝石中的哈希排序?例如

How do you sort a hash in ruby based on the value and then key? For example

h = {4 => 5, 2 => 5, 7 => 1}

将分类为

[[7, 1], [2,5], [4, 5]]

我可以根据执行的值进行排序

I can sort based on the value by doing

h.sort {|x,y| x[1] <=> y[1]}

但是我不知道如何根据值进行排序,如果值相同则输入键

but I can't figure out how to sort based on value and then key if the values are the same

推荐答案

h.sort_by {|k, v| [v, k] }

这利用了Array混入Comparable并按元素定义<=>的事实.

This uses the fact that Array mixes in Comparable and defines <=> element-wise.

请注意,以上等同于

h.sort_by {|el| el.reverse }

等效于

h.sort_by(&:reverse)

可能更具可读性.

如果知道通常Hash通常首先按键排序,然后按值排序,那么上面的内容应该很明显.也许有一点评论:

If you know that Hashes usually sort by key first, then by value, the above should be obvious. Maybe with a small comment:

h.sort_by(&:reverse) # sort by value first, then by key


注意:如果您只是想委托给某个属性的<=>方法(即,通过键而不是常规比较函数进行排序),通常首选使用sort_by而不是sort.它更容易阅读.通常,它碰巧也更快,但是可读性方面更为重要.


Note: if you simply want to delegate to some property's <=> method, (i.e. sort by a key rather than a general comparison function) it is generally prefered to use sort_by instead of sort. It's much easier to read. Generally, it also happens to be faster, but the readability aspect is the more important one.

您真的应该只在绝对必要的情况下编写自己的比较函数.

You should really only write your own comparison function if absolutely necessary.

因此,您的无效示例最好写为

So, your non-working example would better be written as

h.sort_by {|el| el[1] }

我个人更喜欢在块参数列表中使用解构绑定,而不是使用el[0]el[1]:

Personally, I prefer to use destructuring bind in the block parameter list, instead of using el[0] and el[1]:

h.sort_by {|key, value| value }

但是,在这种特殊情况下,el[1]也恰好与el.last相同,因此您可以简单地编写

However, in this particular case, el[1] also happens to be identical to el.last, so that you could simply write

h.sort_by(&:last)

这篇关于根据值对红宝石中的哈希进行排序,然后对密钥进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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