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!
Array#values_at does exactly what you need:
array.values_at(*desired_order)
desired_order.map{|i| array[i]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With