tags:

views:

35

answers:

1

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.)

+1  A: 

How about this?

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

Will return an array of arrays of records.

cwninja