Ruby - 选择最近日期的数组条目

时间:2015-08-26 23:44:44

标签: ruby datetime select

如何只返回最近日期时间的哈希值?

list = [ { info: "i am cool", datetime: June 25 5 pm},
         { info: "this is sweet", datetime: June 25 4 pm},
         { info: "it is blue", datetime: June 23 2 pm} ]

3 个答案:

答案 0 :(得分:4)

您可以使用Array#max_by

list.max_by {|o| o[:datetime]}

答案 1 :(得分:0)

您可以使用Array#sort的阻止形式按datetime对其进行排序,然后获取最后一个。

require 'date'

list = [
  { datetime: DateTime.parse("June 25 5pm"), info: "i am cool" },
  { datetime: DateTime.parse("June 25 4pm"), info: "this is sweet" },
  { datetime: DateTime.parse("June 23 2pm"), info: "it is blue" }
]

list.sort do |a, b|
  a[:datetime] <=> b[:datetime]
end.last

答案 2 :(得分:0)

对于五年后寻找此答案的任何人,您可以:

list.filter {|o| o[:datetime] < Date.today}.max