From: 7stud -- Date: 2011-05-01T06:34:59+09:00 Subject: Re: question about working with dates 7stud -- wrote in post #995994: > eggman2001 wrote in post #995956: >> I have a list (in database) of weekday non-holiday dates that goes >> from present back to 1990. From this list, I'd like to pull out dates >> given different kinds of criteria and add them to an array. Examples >> of criteria are: >> - first day of the month for the most recent 5 years. Perhaps obvious, >> but the first weekday non-holiday of the month isn't necessarily day 1 >> (i.e. 5/1). >> > > All it takes is a little math: > > > require 'date' > > #Create array of all weekday dates for last five years > #(probably faster than pulling them out of a database): > > date_arr = [] > previous_years = 5 > Hmmmm...looks like the following line got deleted somehow: today = Date.today > > 1.upto(previous_years * 365) do |i| > new_date = today - i > > next if [6,0].include?(new_date.wday) > date_arr << new_date > end > ======== > > You could benchmark whether adding the check below would be faster: > > last_result = results[-1] > > if last_result.is_a?(Date) and last_result.month == month > next > end This would be better: last_result = results[-1] begin next if last_result.month == month rescue NoMethodError #do nothing end That rescue handles the initial case when the results array is empty, and results[-1] returns nil. After the array has one element, then only the if check will be executed. -- Posted via http://www.ruby-forum.com/.