Reputation: 1171
I have a hash of some random order and the keys of that hash are are in an array.
my_array = ['ONE', 'TWO', 'THREE']
my_hash = { 'THREE' => "this is the third",
'ONE' => "this is the first",
'TWO' => 'second' }
How to get this ordered in a way where
new_hash = { 'ONE' => "this is the first",
'TWO' => 'second',
'THREE' => "this is the third" }
Upvotes: 0
Views: 48
Reputation: 9508
Try this:
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"}
Upvotes: 1