Ruby Hash#sort_by

转载于:https://medium.com/@florenceliang/some-notes-about-using-hash-sort-by-in-ruby-f4b3a700fc33

仅用于笔记学习!

Ruby#sort and #sort_by methods are powerful: We can easily arrange the result we want, such as sort the names by alphabetical order or the name’s length. Surprisingly, there are not many examples in Ruby document library for this useful tool. Therefore, I would like to explore some use cases of #sort_by and #sort, specifically for Hash.

  • #sort will return a new array

First thing to note that #sort/#sort_by will return a new array. Suppose we have a hash:

hash = {a:1, b:2, c:4, d:3, e:2}

# When we call sort on this hash, it will convert hash into a nested array:

hash.sort
# => [[:a, 1], [:b, 2], [:c, 4], [:d, 3], [:e, 2]]

Therefore, if we want to return the sorted hash in hash format, we need to call #to_h after #sort.

 

Sort by Hash values in ascending and descending order

So what if we want to sort by hash values instead of the key’s order? Here comes the #sort_by method:

hash.sort_by {|k, v| v}
# => [[:a, 1], [:b, 2], [:e, 2], [:d, 3], [:c, 4]]

By default, Ruby returns the value in ascending order. If we want Ruby to return the value in descending order without using #reverse method, we can do this:

hash.sort_by {|k, v| -v}
# => [[:c, 4], [:d, 3], [:b, 2], [:e, 2], [:a, 1]]

Sort by Hash values and keys at the same time

 Finally, suppose we have a long list of hash like below:

hash = {“w”=>2, “k”=>1, “l”=>2, “v”=>5, “d”=>2, “h”=>4, “f”=>1, “u”=>1, “p”=>1, “j”=>1}

With this hash, we want to do two things. First, sort the hash by the values in descending order . Then, sort it by letter’s alphabetical order. We can easily achieved this as below:

hash.sort_by {|k, v| [-v, k]}
# => [[“v”, 5], [“h”, 4], [“d”, 2], [“l”, 2], [“w”, 2], [“f”, 1], [“j”, 1], [“k”, 1], [“p”, 1], [“u”, 1]]

I hope the use cases will help us write cleaner and shorter codes in Ruby.

 

posted @   鞋带松了  阅读(90)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示