在Ruby中,如何按字母顺序按键值对哈希进行排序?

时间:2015-03-04 16:21:59

标签: ruby

假设我有一个哈希, {" c":1," b":2," a":3} 如何对哈希进行排序,使元素按键值排序?

2 个答案:

答案 0 :(得分:1)

myh = {“c”=> 1,“b”=> 2,“a​​”=> 3}

myh.sort

=> [[“a”,3],[“b”,2],[“c”,1]]

答案 1 :(得分:1)

{"c" => 1, "b" => 2, "a" => 3}.sort.to_h