在Rails中,我有一个数据集合,需要对其进行过滤,以获得每个月最新创建的数据。最优化的方法是什么?
e.g
["2012-1-2","2012-1-18", "2012-1-5", "2012-2-15","2012-2-23","2012-2-4"]结果应该是
["2012-1-18, "2012-2-23", ..]发布于 2012-12-13 01:49:59
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-12-13 03:34:34
["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}}发布于 2012-12-13 01:39:00
这应该是可行的:
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]}但是,如果这些日期是从数据库表中出来的,也许您可以考虑在那里对其进行排序。这会更快一些(特别是如果有很多记录的话)。
https://stackoverflow.com/questions/13851484
复制相似问题