我有一系列哈希。
每个哈希都有3个键值(计划,数字,时间)
所以它会像:
[0]{plan => "my_plan", number=> 1234, time =>"2016-03-02T13:56:02.000-05:00" }
[1]{plan => "my_plan", number=> 1234, time =>"2016-03-02T14:56:02.000-05:00" }
[2]{plan => "my_plan", number=> 1234, time =>"2016-03-02T13:59:02.000-05:00" }
[3]{plan => "my_plan", number=> 1234, time =>"2016-03-02T12:56:02.000-05:00" }
[4]{plan => "my_plan", number=> 4444, time =>"2016-03-02T16:42:02.000-05:00" }
[5]{plan => "my_plan", number=> 4444, time =>"2016-03-02T16:45:02.000-05:00" }
[6]{plan => "my_plan", number=> 4444, time =>"2016-03-02T16:44:02.000-05:00" }
[7]{plan => "my_plan", number=> 4444, time =>"2016-03-02T16:50:02.000-05:00" }
等等
我希望保留最新时间(最长时间)。
所以数字是“1234”,我想保留这一行:
{plan => "my_plan", number=> 1234, time =>"2016-03-02T14:56:02.000-05:00" }
并丢弃其余部分。
对于号码“4444”,我会保留:
{plan => "my_plan", number=> 4444, time =>"2016-03-02T16:50:02.000-05:00" }
因为它是具有该数字最大日期的那个
答案 0 :(得分:4)
input = [
{plan: "my_plan", number: 1234, time: "2016-03-02T13:56:02.000-05:00" },
{plan: "my_plan", number: 1234, time: "2016-03-02T14:56:02.000-05:00" },
{plan: "my_plan", number: 1234, time: "2016-03-02T13:59:02.000-05:00" },
{plan: "my_plan", number: 1234, time: "2016-03-02T12:56:02.000-05:00" },
{plan: "my_plan", number: 4444, time: "2016-03-02T16:42:02.000-05:00" },
{plan: "my_plan", number: 4444, time: "2016-03-02T16:45:02.000-05:00" },
{plan: "my_plan", number: 4444, time: "2016-03-02T16:44:02.000-05:00" },
{plan: "my_plan", number: 4444, time: "2016-03-02T16:50:02.000-05:00" }
]
input.group_by { |e| e[:number] }
.values
.map { |vals| vals.sort_by { |e| e[:time] }.last }
#⇒ [
# [0] {
# :number => 1234,
# :plan => "my_plan",
# :time => "2016-03-02T14:56:02.000-05:00"
# },
# [1] {
# :number => 4444,
# :plan => "my_plan",
# :time => "2016-03-02T16:50:02.000-05:00"
# }
# ]
无论您是否可以自由使用精彩的Hashie::Mash
实施,它都更具表现力:
require 'hashie'
input.map { |h| Hashie::Mash.new(h) }
.group_by(&:number)
.values
.map { |vals| vals.sort_by(&:time).last }
NB 日期时间值是否可能位于不同的时区,在排序前将字符串显式转换为Time
实例更安全:
input.group_by { |e| e[:number] }
.values
.map { |vals| vals.sort_by { |e| Time.parse e[:time] }.last }