Shpigford Shpigford - 1 year ago 68
Ruby Question

Group by month+year with counts

I have a table of

that has a
column named

I want to get a list of all the month + year combinations present along with the number of albums released in that month/year.

So, the output might be something like:

  • November 2016 - 11

  • October 2016 - 4

  • July 2016 - 19

  • December 2015 - 2

Ruby 2.3.1 w/ Rails 5 on Postgres 9.6, FWIW.

Answer Source

I'm assuming your table is singular Album per Rails convention. If not, consider changing it. { |album| [Date::MONTHNAMES[],].join(' ') }
  .each_with_object( { |month_year, counts| counts[month_year] += 1 }


The .map method iterates over the albums and returns an array of strings consisting of ["month year", "month year", ... ].

The .each_with_object method is a standard counting algorithm that returns a hash with a count for each unique array item.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download