absessive
absessive

Reputation: 1171

How do I sort a ruby hash by keys according to the order of those keys in an array?

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

Answers (1)

Sagar Pandya
Sagar Pandya

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

Related Questions