From: x1 Date: 2006-10-12T12:44:20+09:00 Subject: Re: Counting Frequency of Values in an Array (And Sorting by Frequency?) and.. so you're aware.. my hacky code was something like this: items = {} ["a", "a", "a", "b", "c", "c"].each do |i| if items.include? i items[i] += 1 else items[i] = 1 end end items.sort {|a,b| a[1]<=>b[1]}.reverse.each do |a, b| puts a + ":" + b.to_s end horrific eh? On 10/11/06, x1 wrote: > Wow Capaldo, that worked! I fear for the next java programmer who has > to make sense of my code when I leave ;-) > > To reverse sort, I added .reverse.. Here's the final product: > puts ["a", "a", "a", "b", "c", "c"].inject(Hash.new(0)) { |hash, item| > hash[item] += 1 > hash }.sort_by { |k, v| v }.reverse.map { |k, v| "#{k}:#{v}" } > > Thanks so much. > > Nakada, I look forward to using it in 1.9 :-) > > On 10/11/06, Nobuyoshi Nakada wrote: > > Hi, > > > > At Thu, 12 Oct 2006 11:52:19 +0900, > > x1 wrote in [ruby-talk:219218]: > > > 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 ? > > > > FYI, Enumerable in 1.9 has that method. > > > > -- > > Nobu Nakada > > > > >