Skip to content

Instantly share code, notes, and snippets.

@jordan-brough
Created February 27, 2012 19:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jordan-brough/1926410 to your computer and use it in GitHub Desktop.
Save jordan-brough/1926410 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