按键排序哈希,在Ruby中返回哈希 [英] Sort hash by key, return hash in Ruby
本文介绍了按键排序哈希,在Ruby中返回哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
h = { a=> 1,c=> 3,b=> 2,d=> 4}
#=> {a=> 1,c=> 3,b=> 2,d=> 4}
哈希[h.sort]
#=> {a=> 1,b=> 2,c=> 3,d=> 4}
解决方案
在Ruby 2.1中很简单:
h.sort.to_h
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}
解决方案
In Ruby 2.1 it is simple:
h.sort.to_h
这篇关于按键排序哈希,在Ruby中返回哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文