From: Phrogz Date: 2006-10-12T12:10:07+09:00 Subject: Re: Counting Frequency of Values in an Array (And Sorting by Frequency?) x1 wrote: > I was able to hack it by using a hash doing various things to it.. but > it didn't seem "rubyish". What could be more ruby-ish than monkeypatching a built-in class and using inject in the process? class Array def counts inject( Hash.new(0) ){ |hash,element| hash[ element ] +=1 hash } end def counts_up counts.sort_by{ |k,v| v } end def counts_down counts.sort_by{ |k,v| -v } end end a = ["a", "a", "a", "b", "c", "c"] p a.counts, a.counts_up, a.counts_down #=> {"a"=>3, "b"=>1, "c"=>2} #=> [["b", 1], ["c", 2], ["a", 3]] #=> [["a", 3], ["c", 2], ["b", 1]]