Sort an array according to the elements of another array
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)