【问题标题】:One liner to chunk Ruby objects into sub arrays based on Date/Timeframe?一种基于日期/时间框架将 Ruby 对象分块为子数组的衬垫?
【发布时间】:2010-09-29 08:27:55
【问题描述】:

假设我有 1200 个带有 created_at 属性的 ActiveRecord 对象,并且一年中每个月都会创建 100 个。遍历记录并按月分块的唯一 ruby​​ 方法是什么?

[record_a, record_b, record_c, ...].group_by(&:month) do |month, records_for_the_month|
  records_for_the_month.each ...
end

...假设我没有 month 方法/属性,并且我可能希望按任意时间范围(4 周、季度、季节、周等)进行分块

【问题讨论】:

    标签: ruby group-by


    【解决方案1】:

    这个怎么样?

    Foo.all.group_by{|v| v.created_at.beginning_of_month }.values
    

    将返回一个记录数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多