From: Robert Klemme Date: 2008-03-25T19:23:50+09:00 Subject: Re: numbers of a record in an array 2008/3/25, Jesús Gabriel y Galán : > On Tue, Mar 25, 2008 at 10:09 AM, Bu Mihai wrote: > > a have an array array=["a","b","c","a","b"] > > how can i find the numbers of "a", "b","c" items in the array? > > > Here's one way: > > irb(main):006:0> a = %w{a b a c b a c c} > => ["a", "b", "a", "c", "b", "a", "c", "c"] > irb(main):007:0> h = Hash.new {|h,k| h[k] = 0} > => {} > irb(main):008:0> a.each {|x| h[x] += 1} > => ["a", "b", "a", "c", "b", "a", "c", "c"] > irb(main):009:0> h > => {"a"=>3, "b"=>2, "c"=>3} Here's another irb(main):001:0> a = %w{a b a c b a c c} => ["a", "b", "a", "c", "b", "a", "c", "c"] irb(main):002:0> a.inject(Hash.new(0)){|cnt,e| cnt[e]+=1; cnt} => {"a"=>3, "b"=>2, "c"=>3} Jesús, note that you do not need the block form of Hash.new because of the way + works. It is sufficient to make 0 the default element. Kind regards robert -- use.inject do |as, often| as.you_can - without end