按键排序哈希,在 Ruby 中返回哈希 [英] Sort hash by key, return hash in Ruby
本文介绍了按键排序哈希,在 Ruby 中返回哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是对哈希进行排序并返回哈希对象(而不是数组)的最佳方法吗:
Would this be the best way to sort a hash and return Hash object (instead of Array):
h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
# => {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
Hash[h.sort]
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4}
推荐答案
在 Ruby 2.1 中很简单:
In Ruby 2.1 it is simple:
h.sort.to_h
这篇关于按键排序哈希,在 Ruby 中返回哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文