Ruby: Sort array of objects based on array of integers

前端 未结 3 2046
梦毁少年i
梦毁少年i 2021-01-20 03:17

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 l

3条回答
  •  长发绾君心
    2021-01-20 03:48

    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"]
    

提交回复
热议问题