Created
February 27, 2012 19:14
-
-
Save jordan-brough/1926410 to your computer and use it in GitHub Desktop.
ruby count_by using group_by
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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