From: Logan Capaldo Date: 2006-10-12T12:14:05+09:00 Subject: Re: Counting Frequency of Values in an Array (And Sorting by Frequency?) On Thu, Oct 12, 2006 at 11:52:19AM +0900, x1 wrote: > 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 ? > array.select { |i| i == 'a' }.length or array.inject(0) { |count, item| count += 1 if item == 'a'; count } > 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 > > > Or sorted from least to greatest: > #desired output: > b: 1 > c: 2 > a: 3 > > I was able to hack it by using a hash doing various things to it.. but > it didn't seem "rubyish". > As you say: puts array.inject(Hash.new(0)) { |hash, item| hash[item] += 1 hash }.sort_by { |k, v| v }.map { |k, v| "#{k}:#{v}" } > Thank you for any input.