From: "Jesús Gabriel y Galán" Date: 2010-03-28T06:11:27+09:00 Subject: Re: Help to get value from abject inside an array On Sat, Mar 27, 2010 at 10:01 PM, Nicolas 2b wrote: > Hi, > > My problem use RoR object but is ruby oriented so I post here. > I got an array with lot of objects (type 'Product') like this (only 4 > here) : > > [#, # 2>, #, # company_id: 4>] > > What I want to do is iterate on the array and for each company_id, know > how much products have the same company_id. > I get the company_id like this : products.collect(&company_id).uniq > > but after I don't know how to get an array like this : [1 => 22, 2 => > 15, 3 => 9] I assume you want to get a hash that relates the companyId with the number of products of that company: irb(main):016:0> Product = Struct.new :companyId, :productId => Product irb(main):017:0> a = [Product.new(1, 10), Product.new(1,11), Product.new(2,20), Product.new(3,30)] => [#, #, #, #] irb(main):018:0> h = Hash.new(0) => {} irb(main):020:0> a.each {|p| h[p[:companyId]] += 1} => [#, #, #, #] irb(main):022:0> h => {1=>2, 2=>1, 3=>1} Jesus.