Sort an array according to the elements of another array Sort an array according to the elements of another array ruby ruby

Sort an array according to the elements of another array


I'll be surprised if anything is much faster than the obvious way:

a2.sort_by{|x| a1.index x.id}


hash_object = objects.each_with_object({}) do |obj, hash|   hash[obj.object_id] = objend[1, 2, 3, 4, 5].map { |index| hash_object[index] }#=> array of objects in id's order

I believe that the run time will be O(n)


I like the accepted answer, but in ActiveSupport there is index_by which makes creating the initial hash even easier. See Cleanest way to create a Hash from an Array

In fact you could do this in one line since Enumerable supports index_by as well:

a2.index_by(&:id).values_at(*a1)