- It is very easy to sort a hash base on the order of an existed array, we can do this by this code:
hash.sort_by{|k, v| arr.index(k)}
- And if you want to sort an array of array based on the order of another array:
arr2.sort_by { |e| arr1.index(e[0]) }
#the other way
arr2.sort_by { |element| arr1.index(element.first) }
#the more other way
arr2.values_at(*arr2.map { |str,_| arr1.index(str) })
#one more other way
hash_object = objects.each_with_object({}) do |obj, hash|
hash[obj.object_id] = obj
end
[1, 2, 3, 4, 5].map { |index| hash_object[index] }
#see, so suprising!