From: Kenichi Kamiya Date: 2012-01-17T19:58:05+09:00 Subject: Re: uniq with count; better way? Abinoam, thank you for get the benchmarks. I guess the different of spped from generating objects. They generate minimal objects which Object#tap and Enumerable#each_with_object. ------------------------------------------------------------------------------- Ralph, I like #1 for comprehensibility meaning # looks "construct Hash instance from inner subscript" Hash[] # looks "collect the own values" a.group_by{|n|n} # counting map{|k, v|[k, v.size]}] # if Hash has own map https://gist.github.com/1626034 ------------------------------------------------------------------------------- I like #2 for comprehensibility, clear name-space, and speed meanings # comprehensibility # looks like "list comprehension" tap{|h|a.each{|n|h[n] += 1}} # clear name-space no make variables for out of block # speed meanings look Abinoam's benchmarks # if Enumerable has method for this case https://gist.github.com/1625981 2012/1/17 Ralph Shnelvar : > Kenichi, > > Monday, January 16, 2012, 9:21:51 AM, you wrote: > > > > KK> 2012/1/17 Ralph Shnelvar : >>> a = [4,5,6,4,5,6,6,7] >>> >>> result = Hash.new(0) >>> a.each { |x|  result[x] += 1 } >>> >>> p result >>> >>> >>> >>> The result I am getting >>>   {4=>2, 5=>2, 6=>3, 7=>1} >>> is what I want. >>> >>> Is there a better way; perhaps using uniq? >>> >>> > > > KK> I like this > > KK> a = [4,5,6,4,5,6,6,7] > > KK> # 1 > KK> p Hash[a.group_by{|n|n}.map{|k, v|[k, v.size]}] > > KK> # 2 > KK> p Hash.new(0).tap{|h|a.each{|n|h[n] += 1}} > > > I like #2.  I can understand it.  I'm still having trouble wrapping my head around #1. > > > Having said that, is your #2 better than mine in any dimension (comprehensibility and/or speed of execution? > > > -- Kenichi Kamiya