From: Robert Klemme Date: 2007-06-28T19:10:01+09:00 Subject: Re: Can i calculate the data number in array? On 28.06.2007 10:44, Axel Etzold wrote: > Dear Cool, > > maybe this is what you want: > > class Array > > > > def count > > k=Hash.new(0) > > self.each{ |x| k[x]+=1 } > > k > > end > > > > end > > > my_array = ["a", "a", "a", "b", "b", �c�, "c", "c","d", "d", "e"] > my_array.count > > It gives you a Hash, though, and the numbers are Integers, > not Strings, but this seems more reasonable :) Yes, I'd agree. Having tuples as return value is better because then you maintain relationship between items and item count. Btw, thanks for leaving the inject solution to me. :-) irb(main):005:0> a = %w{a a a b b c c c d d e} => ["a", "a", "a", "b", "b", "c", "c", "c", "d", "d", "e"] irb(main):006:0> a.inject(Hash.new(0)) {|h,x| h[x]+=1; h} => {"a"=>3, "b"=>2, "c"=>3, "d"=>2, "e"=>1} irb(main):007:0> a.inject(Hash.new(0)) {|h,x| h[x]+=1; h}.sort => [["a", 3], ["b", 2], ["c", 3], ["d", 2], ["e", 1]] Kind regards robert