【发布时间】:2011-02-07 16:56:27
【问题描述】:
我有一个 Post 对象的集合,我希望能够根据这些条件对它们进行排序:
- 首先,按类别(新闻、事件、实验室、作品集等)
- 然后按日期(如果是日期)或按位置(如果为其设置了特定索引)
有些帖子会有日期(新闻和事件),其他帖子会有明确的职位(实验室和作品集)。
我希望能够调用posts.sort!,因此我已覆盖<=>,但我正在寻找根据这些条件进行排序的最有效方法。下面是一个伪方法:
def <=>(other)
# first, everything is sorted into
# smaller chunks by category
self.category <=> other.category
# then, per category, by date or position
if self.date and other.date
self.date <=> other.date
else
self.position <=> other.position
end
end
看来我实际上必须分别进行两次排序,而不是将所有内容都塞进那个方法中。比如sort_by_category,然后是sort!。最红宝石的方法是什么?
【问题讨论】:
标签: ruby sorting operators comparison-operators spacecraft-operator