I want to have a hash with its elements sorted with a custom sort order.

Consider the example

#---------------------

test_hash = {“A” => “first”, “B” => “second”}

puts test_hash.keys.join(", ")

order_arr = [“B”, “A”]

test_hash.sort do |x,y|

(order_arr.index(x[0])?order_arr.index(x[0]):order_arr.length) <=>

(order_arr.index(y[0])?order_arr.index(y[0]):order_arr.length)

end

puts test_hash.keys.join(", ")

#----------------------

Output:

A, B

A, B

=> true

I want to order such that the keys (or values) when returned in an array

are

ordered.

Obviously the above snipper does *not* work because Hash#sort does not

sort

the Hash but returns an array of arrays with elements sorted according

to

sort block.

I can maintain a parallel array of sorted keys but it is kind of kludgy.

Can I sort the hash “in place” such that the Hash#keys and Hash#values

return sorted results, without me having to maintain this array of

arrays

separately?

TIA