Ruby: sorting an array of objects based on an array of integers

This seems pretty straightforward and should have been asked before, but everything I find in Stack Overflow doesn't seem to work. I have an array of 4 objects, and I would like to reorder it in a specific order. So it looks like this:

array = [Obj1, Obj2, Obj3, Obj4] 

I have another array of integers that represent the desired index order:

 desired_order = [2,3,0,1] 

So, I would like the array be correct after ordering:

 array = [Obj3, Obj4, Obj1, Obj2] 

I already realized that sort_by is a method to use, but I cannot come up with the correct syntax. Any help is much appreciated!

+4
source share
3 answers

Array # values_at does exactly what you need:

 array.values_at(*desired_order) 
+7
source
 desired_order.map{|i| array[i]} 
+5
source

If you already have indexes, you can simply map them to objects:

 array = %w[obj1 obj2 obj3 obj4] desired_order = [2,3,0,1] desired_order.map{|idx| array[idx]} # => ["obj3", "obj4", "obj1", "obj2"] 
+1
source

All Articles