Ruby: Sort array of objects based on array of integers

試著忘記壹切 提交于 2020-01-21 11:52:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!