Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Sort array of objects based on array of integers

This seems like its fairly simple, and should have been asked before, but everything I find on Stack Overflow doesn't seem to work. I have an array of 4 objects, and I'd like to re-order it in a particular order. So, it looks like this:

array = [Obj1, Obj2, Obj3, Obj4]

I have another array of integers which represent the desired order of the indices:

desired_order = [2,3,0,1]

So what I would like to see after ordering array properly is:

array = [Obj3, Obj4, Obj1, Obj2]

I've already figured sort_by is the method to use, but I can't seem to come up with the proper syntax. Any help is greatly appreciated!

like image 646
David Savage Avatar asked Dec 11 '22 19:12

David Savage


2 Answers

Array#values_at does exactly what you need:

array.values_at(*desired_order)
like image 84
tokland Avatar answered Dec 14 '22 23:12

tokland


desired_order.map{|i| array[i]}
like image 29
sawa Avatar answered Dec 15 '22 00:12

sawa