我有一些随机顺序的哈希,并且该哈希的键位于数组中。
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" }
答案 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"}