给定一系列活动记录
jobs = [#<Job _id: 1, created_at: 2014-07-15 19:18:40 UTC, organization: "Acme In.c">,
#<Job _id: 3, created_at: 2014-05-20 09:27:38 UTC, organization: "Baxter">,
#<Job _id: 2, created_at: 2014-11-25 12:21:00 UTC, organization: "Wizard">,
#<Job _id: 3, created_at: 2015-01-15 07:20:10 UTC, organization: "Baxter">]
我如何先按organization
按升序排序A-> Z,然后按created_at
降序排列,以此结束...
jobs = [#<Job _id: 1, created_at: 2014-07-15 19:18:40 UTC, organization: "Acme In.c">,
#<Job _id: 3, created_at: 2015-01-15 07:20:10 UTC, organization: "Baxter">,
#<Job _id: 3, created_at: 2014-05-20 09:27:38 UTC, organization: "Baxter">,
#<Job _id: 2, created_at: 2014-11-25 12:21:00 UTC, organization: "Wizard">]
我试图做jobs.sort_by{|j| [j.organization, j.created_at]}
但是我不确定如何指定多个asc / desc规则,而我得到的最接近的规则按组织排序但是按创建排序给我最老的最新而不是最新到最旧。我也尝试先分组然后排序,但我也无法让它工作。任何帮助,如果感激。
答案 0 :(得分:3)
一个好方法是像这样使用sort
和<=>
以及nonzero?
:
jobs.sort{|a,b|
(a.organization <=> b.organization).nonzero? ||
(b.created_at <=> a.created_at)
}
此代码说:
独立于ActiveRecord的示例代码:
require 'time'
require 'ostruct'
jobs = [
OpenStruct.new(_id: 1, created_at: Time.parse("2014-07-15 19:18:40 UTC"), organization: "Acme Inc"),
OpenStruct.new(_id: 3, created_at: Time.parse("2014-05-20 09:27:38 UTC"), organization: "Baxter"),
OpenStruct.new(_id: 2, created_at: Time.parse("2014-11-25 12:21:00 UTC"), organization: "Wizard"),
OpenStruct.new(_id: 3, created_at: Time.parse("2015-01-15 07:20:10 UTC"), organization: "Baxter")
]
答案 1 :(得分:0)
如
中所述尝试jobs.order("organization ASC", "created_at DESC")
或以下
jobs.order("organization ASC").order("created_at DESC")