Skip to content

Instantly share code, notes, and snippets.

@creadone
Forked from jordan-brough/gist:1926410
Created February 28, 2017 10:42
Show Gist options
  • Save creadone/47b2323ba0326eca13c463cf234ec230 to your computer and use it in GitHub Desktop.
Save creadone/47b2323ba0326eca13c463cf234ec230 to your computer and use it in GitHub Desktop.
ruby count_by using group_by
# See http://jordan.broughs.net/archives/2012/07/enumerablecount_by-for-ruby
# 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
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment