如何根据数组中键的顺序按键对ruby哈希进行排序?

时间:2016-11-22 20:47:43

标签: ruby hash

我有一些随机顺序的哈希,并且该哈希的键位于数组中。

my_array = ['ONE', 'TWO', 'THREE']
my_hash = { 'THREE' => "this is the third", 
            'ONE' => "this is the first",
            'TWO' => 'second' }

如何以

的方式订购
new_hash = { 'ONE' => "this is the first",
             'TWO' => 'second',
             'THREE' => "this is the third" }

1 个答案:

答案 0 :(得分:1)

试试这个:

my_array = ['ONE', 'TWO', 'THREE']
my_hash = { 'THREE' => "this is the third", 
            'ONE' => "this is the first",
            'TWO' => 'second' }

my_array.zip(my_array.map {|s| my_hash[s]}).to_h
#=> {"ONE"=>"this is the first", "TWO"=>"second", "THREE"=>"this is the third"}