One liner for breaking Ruby objects into auxiliary arrays based on Date / Timeframe?

Let's say I have 1200 ActiveRecord objects with an attribute created_at, and 100 were created every month for a year. What is one ruby ​​ruby ​​path for repetition and recording per 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 method / attribute month, and I might want to cut out any arbitrary time frames (4 weeks, a quarter of a year, season, weeks, etc.).

+3
source share
1 answer

How about this?

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

Will return an array of record arrays.

+2
source

Source: https://habr.com/ru/post/1767071/


All Articles