Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$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}
@kachick

This comment has been minimized.

Copy link
Owner Author

kachick commented Jan 17, 2012

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}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.