From: 7stud -- Date: 2012-12-26T16:34:04+09:00 Subject: Re: Accumulate total count for each month Soichi Ishida wrote in post #1090212: > > Normally, when counting the number of each word occurred in a file, > using hash can help (each word as a key). But this case, it is not that > simple because the key is date object. > > Do you have better ideas for counting the number of events each month? > require 'date' date_times1 = (1..12).map do |month| DateTime.new(2012,month,25,4,5,6) end date_times2 = (1..6).map do |month| DateTime.new(2012,month,25,4,5,6) end date_times = date_times1 + date_times2 results = Hash.new {|hash, key| hash[key] = []} date_times.each do |dt| results[dt.month] << dt end (1..12).each do |month| puts "month %s:" % month results[month].each do |event| puts "\t%s" % event end end --output:-- month 1: 2012-01-25T04:05:06+00:00 2012-01-25T04:05:06+00:00 month 2: 2012-02-25T04:05:06+00:00 2012-02-25T04:05:06+00:00 month 3: 2012-03-25T04:05:06+00:00 2012-03-25T04:05:06+00:00 month 4: 2012-04-25T04:05:06+00:00 2012-04-25T04:05:06+00:00 month 5: 2012-05-25T04:05:06+00:00 2012-05-25T04:05:06+00:00 month 6: 2012-06-25T04:05:06+00:00 2012-06-25T04:05:06+00:00 month 7: 2012-07-25T04:05:06+00:00 month 8: 2012-08-25T04:05:06+00:00 month 9: 2012-09-25T04:05:06+00:00 month 10: 2012-10-25T04:05:06+00:00 month 11: 2012-11-25T04:05:06+00:00 month 12: 2012-12-25T04:05:06+00:00 -- Posted via http://www.ruby-forum.com/.