Created
January 17, 2012 09:49
-
-
Save kachick/1625981 to your computer and use it in GitHub Desktop.
an aproach to http://www.ruby-forum.com/topic/3446541
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
$VERBOSE = true | |
module Enumerable | |
def count_by | |
return to_enum(__method__) unless block_given? | |
Hash.new(0).tap{|h| | |
each{|v|h[yield v] += 1} | |
} | |
end | |
end | |
list = [4, 5, 6, 4, 5, 6, 6, 7] | |
p list.group_by | |
p list.group_by{|v|v} | |
p list.group_by{|v|v * 2} | |
p list.count_by | |
p list.count_by{|v|v} | |
p list.count_by{|v|v * 2} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in ruby-1.9.3p0
Enumerator: [4, 5, 6, 4, 5, 6, 6, 7]:group_by
{4=>[4, 4], 5=>[5, 5], 6=>[6, 6, 6], 7=>[7]}
{8=>[4, 4], 10=>[5, 5], 12=>[6, 6, 6], 14=>[7]}
Enumerator: [4, 5, 6, 4, 5, 6, 6, 7]:count_by
{4=>2, 5=>2, 6=>3, 7=>1}
{8=>2, 10=>2, 12=>3, 14=>1}