Creating a sorted hash counting the occurrences of a number in an array I figured something like this:

a= [1, 2, 3, 2, 2, 2, 3, 1, 1, 1, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a.inj­ect({}) { |h, el| h[el]­ = a.cou­nt(el) if h[el]­.nil? ; h }.sor­t_by {|k,v­| v}.re­verse.inje­ct({}) { |h, el| h[el[­0]] = el[1]­ ; h}


This outputs:

=&gt; {0=&gt;10, 4=&gt;9, 2=&gt;5, 1=&gt;4, 3=&gt;2}


But it seems like a clunky solution that does to many passes over the "same" thing.

What would be a good way to do this from different viewpoints?

I.e:


an "impress your Java friends" (small one-liner not used in production)
Performance
Easily read
Not sure which viewpoint this would be, but this is what I came up with:

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}]


Update: I'm not thrilled with this, but this one sorts by the occurrence count, descending.

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}.sort_by {|a| a[1]}.reverse]