Skip to content

Instantly share code, notes, and snippets.

@kachick
Created January 17, 2012 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kachick/1625981 to your computer and use it in GitHub Desktop.
Save kachick/1625981 to your computer and use it in GitHub Desktop.
$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
Copy link
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