Hi, >From: x1 <caldridge / gmail.com> >Reply-To: ruby-talk / ruby-lang.org >To: ruby-talk / ruby-lang.org (ruby-talk ML) >Subject: Counting Frequency of Values in an Array (And Sorting by >Frequency?) >Date: Thu, 12 Oct 2006 11:52:19 +0900 > >Is there no method for an array that will tell me the # of occurrences >for an item? > >IE: ["a", "a", "a", "b", "c", "c"].count("a") #producing 3 ? > You can use ["a", "a", "a", "b", "c", "c"].grep("a").size >I almost thought that rindex would do the trick when looking at the >class docs but.. the example was just engineered to trick me :-( > >I realize I could pass these to a block and count but.. wanted to make >sure it didn't exist. If not, why? Thank you.. ( I did search btw.. no >avail ) > >Also, what's the best way of printing out each unique item and the >number of times it occurs, sorted by numerically by the number of >times it occurs? > >IE: in my example above, i'd like to see (sorted by occurrence >greatest to least) >#desired output: >a: 3 >c: 2 >b: 1 > array.uniq.sort_by{|x|array.grep(x).size}.reverse.each{|x|puts "#{x}: #{array.grep(x).size}"} > >Or sorted from least to greatest: >#desired output: >b: 1 >c: 2 >a: 3 > array.uniq.sort_by{|x|array.grep(x).size}.each{|x|puts "#{x}: #{array.grep(x).size}"} Regards, Park Heesob