Enumerable#count_by for Ruby

Handy function for inspecting (counting) array-like data. Usage:

> [9,10,11,11,11,10].count_by(&:odd?)
=> {true=>4, false=>2}

>> class Foo < Struct.new(:x); end
>> [Foo.new("a"), Foo.new("b"), Foo.new("a")].count_by(&:x)
=> {"a"=>2, "b"=>1}

Source: (I put the first of these in my ~/.irbrc file)

# Ruby >= 1.8.7 (incl 1.9.x)

module Enumerable
  def count_by(&block)
    Hash[group_by(&block).map { |key,vals| [key, vals.size] }]
  end
end

OR

# Ruby <= 1.8.6 (Hash#[] behaves differently in <=1.8.6.  note: breaks when group_by key is an array)

module Enumerable
  def count_by(&block)
    Hash[*group_by(&block).map { |key,vals| [key, vals.size] }.flatten]
  end
end