Ruby: Sort array of objects based on array of integers

前端 未结 3 2015
梦毁少年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"]
    
    0 讨论(0)
  • 2021-01-20 03:51
    desired_order.map{|i| array[i]}
    
    0 讨论(0)
  • 2021-01-20 03:58

    Array#values_at does exactly what you need:

    array.values_at(*desired_order)
    
    0 讨论(0)
提交回复
热议问题