如何使用ruby自定义排序

时间:2013-08-01 22:53:02

标签: ruby

我有一个从数据库中提取的对象数组。但是我只能按数据库的升序或降序对它们进行排序,但是我需要按照自定义顺序对它们进行排序。

假设我有一个来自db的对象数组:

arr =  [obj1,obj2,obj3]

其中obj1 has id 1, obj2 has id 2 and obj3 has id 3

但我的排序顺序是3,1,2或者我会有一些ID来决定订单,[3,1,2]

因此,自定义排序的顺序为:

arr =  [obj3,obj1,obj2]

我试过了:

arr.sort_by{|a,b| [3,1,2]}

我一直在阅读有关排序的一些教程和链接,它主要是简单的排序。那么如何实现上述自定义排序呢?

2 个答案:

答案 0 :(得分:3)

你很亲密。 [3,1,2]指定了一个排序,但它没有告诉块如何将它与您的对象相关联。你想要这样的东西:

arr.sort_by {|obj| [3,1,2].index(obj.id) }

因此,比较将按照数组中id的位置顺序排列对象。

或者,使用更明确的sort(您似乎与sort_by略有混淆):

arr.sort do |a,b|
  ordering = [3,1,2]
  ordering.index(a.id) <=> ordering.index(b.id)
end

答案 1 :(得分:2)

这就像@Chuck的答案,但有O(n log n)表现。

# the fixed ordering
ordering = [3, 1, 2]

# a map from the object to its position in the ordering
ordering_index = Hash[ordering.map(&:id).each_with_index.to_a]

# a fast version of the block
arr.sort_by{|obj| ordering_index[obj.id]}