From: "Jesús Gabriel y Galán" Date: 2009-03-25T20:05:20+09:00 Subject: Re: creating an array by reusing code On Wed, Mar 25, 2009 at 11:42 AM, Sijo Kg wrote: > Hi >   I have > all_req = OnRequest.find(:all, :conditions => [status_id = ?',6]) > >   Now i need to create an array of size 12 containing record counts for > month January to December like [recordcountjanuary,recordcountfeb,....] > So for the first month january I tried like > > all_req.select do |r| >  r.created_at.mon == 1 > end >       What i need is reuse the above code I have placed it in a > function But there I have to call it 12 times .How can i avoid this? Maybe this helps (untested): recordcount = (1..12).map do |month| all_req.select {|r| r.created_at.mon == month}.size end Although this does 12 passes through all_req. BTW, if you need the count you need to check the size of the select. Maybe another approach could be using a hash: recordcount = Hash.new(0) all_req.each do |r| recordcount[r.created_at.mon] += 1 end Hope this helps, Jesus.