Abhishek Abhishek - 6 months ago 10
Ruby Question

Sort Hash Keys based on order of same keys in array

I need to sort an Hash according to order of keys present in other array:

hash = { a: 23, b: 12 }
array = [:b, :a]
required_hash #=> { b: 12, a: 23 }


Is there any way to do it in single line?

Answer
hash = { a: 23, b: 12 }
array = [:b, :a]

array.zip(hash.values_at(*array)).to_h
  #=> {:b=>12, :a=>23}

The steps:

v = hash.values_at(*array)
  #=> [12, 23]
a = array.zip(v) 
  #=> [[:b, 12], [[:a, 23]]
a.to_h
  #=> {:b=>12, :a=>23}