问题
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!
回答1:
Array#values_at does exactly what you need:
array.values_at(*desired_order)
回答2:
desired_order.map{|i| array[i]}
回答3:
If you have indexes already, then you can just 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"]
来源:https://stackoverflow.com/questions/13869780/ruby-sort-array-of-objects-based-on-array-of-integers