开发者

One liner to chunk Ruby objects into sub arrays based on Date/Timeframe?

Say I have 1200 ActiveRecord objects with a created_at attribute, and 100 were开发者_运维百科 created each month for a year. What's the one liner ruby way to iterate through the records and chunk them by month?

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

... assuming I don't have a month method/attribute, and I might want to chunk by any arbitrary time frame (4 weeks, quarter year, season, weeks, etc.)


How about this?

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

Will return an array of arrays of records.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜