From: Robert Dober Date: 2007-08-02T01:33:58+09:00 Subject: Re: count : array to array of hashes On 8/1/07, Jean-S�bastien wrote: > Hi, > I'm tryind to count distinct ids from an array (array_of_ids = > [1,2,3,1,2]), and want a result array of hashes looking like it : > result = [{;id=>1,:count=>2},{;id=>2,:count=>2},{;id=>3,:count=>1}] > > i tried it, but it always returns errors : > result = array_of_ids.inject(Array.new){ |a,x| elt = a.find{|h| h[:id] > == x} || {:id => x, :count => 0}; elt[:count] += 1; elt} > > i took my information from this post : > http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/3122212f6db8d7f5/04a7b10da8195cec?lnk=gst&q=array++count&rnum=8#04a7b10da8195cec > > If someone could help. > > regards > > > irb(main):005:0> a=[1,2,3,42,2,2,3] => [1, 2, 3, 42, 2, 2, 3] irb(main):006:0> a.inject([]){|r,ele| r[ele][:count]+=1 rescue r[ele]={:id => ele, :count=>1}; r}.compact => [{:count=>1, :id=>1}, {:count=>3, :id=>2}, {:count=>2, :id=>3}, {:count=>1, :id=>42}] irb(main):007:0> HTH Robert -- [...] as simple as possible, but no simpler. -- Attributed to Albert Einstein