This is just a simple addition to Ruby’s Enumerable that both Dan Bernier and I agreed should be a part of Ruby’s standard library.

# count_by.rb
# License: MIT
# Authors: Benjamin Oakes, Dan Bernier

module Enumerable
  def count_by(&block)
    group_by(&block).map { |criteria, group| [criteria, group.count] }

require 'minitest/spec'
require 'minitest/autorun'

describe 'count_by' do
  it 'counts the groups' do
    counts = %w(a b b c d d e e e e).count_by { |s| s }
    assert_equal(counts, [["a", 1], ["b", 2], ["c", 1], ["d", 2], ["e", 4]])

Update (2019-02-19): This is likely to be added to Ruby 2.7 as tally.