Ruby:基于整数数组对对象数组进行排序

时间:2021-09-16 16:00:43

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:

这看起来很简单,之前应该问过,但我在Stack Overflow上找到的所有内容似乎都不起作用。我有一个包含4个对象的数组,我想按特定顺序重新排序。所以,它看起来像这样:

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!

我已经想过sort_by是要使用的方法,但我似乎无法提出正确的语法。任何帮助是极大的赞赏!

3 个解决方案

#1


7  

Array#values_at does exactly what you need:

数组#values_at正是您所需要的:

array.values_at(*desired_order)

#2


5  

desired_order.map{|i| array[i]}

#3


1  

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

#1


7  

Array#values_at does exactly what you need:

数组#values_at正是您所需要的:

array.values_at(*desired_order)

#2


5  

desired_order.map{|i| array[i]}

#3


1  

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