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?
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}
If
hash = { a:23, b:12 }
array = [:b, :a]
As a one liner:
Hash[array.map{|e| [e, hash[e]]}]
As for ordering, it was some time ago, when ruby changed the implementation where the hash keys are ordered according to insert order. (Before that there was no guarantee that keys would be sorted one way or another).
aandb?