从日期集合中选择每个月的最后日期



在Ruby on Rails中,我有一个需要过滤的数据集合,以获取每个月最近创建的数据。最好的优化方法是什么?

例如

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]

结果应该是

["2012-1-18, "2012-2-23", ..]
def last_in_month(dates)
  dates = dates.map {|date_string| Date.parse(date_string)}
  grouped_by_month = dates.group_by {|date| date.month}
  grouped_by_month.map do |month, dates_in_month|
    dates_in_month.max_by {|d| d.day}
  end
end
last_in_month(your_nested_arrays.flatten)

返回日期对象。

再次转换为字符串:)

last_in_month(your_nested_arrays.flatten).map {|d| d.to_s(:db)}
["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
.group_by{|s| s[/d+-d+/]}
.values
.map{|a| a.max_by{|s| s[/d+z/].to_i}}

这应该有效:

my_date = ["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]
my_date.sort_by{|date| month,day,year=date.split("-");[year,month,day]}

但是,如果这些日期来自数据库表,也许您可以考虑在那里对其进行排序。这会快一点(特别是如果有很多记录)。

["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"].map { |d| Date.parse(p) }.sort.group_by { |d| [d.month, d.year].join('/') }.map { |k,v| v.last.strftime("%Y-%-m-%-d") }

最新更新