简体   繁体   English

在ruby中排序哈希数组

[英]Sort array of hash in ruby

I have an array of hash like this: 我有这样的哈希数组:

[{683=>5}, {689=>2}, {692=>10}]

I want the result like this: 我想要这样的结果:

[{692=>10}, {683=>5}, {689=>2}]

Could any one help me? 有人可以帮我吗?

Use Enumerable#sort_by . 使用Enumerable#sort_by The return value of the block is used as comparison key. 该块的返回值用作比较键。

[{683=>5}, {689=>2}, {692=>10}].sort_by { |h| -h.values[0] }
# => [{692=>10}, {683=>5}, {689=>2}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM