From: lasitha Date: 2009-03-25T20:15:16+09:00 Subject: Re: creating an array by reusing code On Wed, Mar 25, 2009 at 4:12 PM, Sijo Kg wrote: > [...] >   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? Let's build this up a step at a time... monthly_counts = (1..12).map do |month| # call your function here, passing in the month end Depending on the scope of all_req, it may just be easier to inline the function as follows: monthly_counts = (1..12).map do |month| all_req.select {|r| r.created_at.mon == month }.size end However, this is inefficient. We have to make 12 passes over the all_req collection. You can, instead use Enumerable#group_by: all_req.group_by {|r| r.created_at.mon } which will return a hash of items keyed by the month. Getting counts from this is simply a matter of using #map. I'll leave this as an exercise :) Now, having said all that, the most efficient way to do this is probably to use a group_by clause in your finder. Again, left as an exercise (mostly 'cos i don't know AR :) solidarity, lasitha