From: Todd Date: 2005-07-29T13:56:01+09:00 Subject: Re: add_weekdays method Todd wrote: > Chris Roos wrote: > > Hi, > > > > I've just spent some time looking at an add_weekdays method on the Date > > class. > > > > My implementation is as follows. > > > > class Date > > def add_weekdays(days) > > new_date = self > > while days > 0 > > new_date += 1 > > days -= 1 unless (new_date.wday == 6 || new_date.wday == 0) > > end > > new_date > > end > > end > > > > I'm interested to know whether I've a) wasted my time because I could > > have achieved the same thing with an already available object/method b) > > commited any ruby sins and c) whether there are much better ways of > > implementing this? > > > > Chris > > Looks like you want to skip weekends. I might do it this way... > > class Date > def add_weekdays(days) > new_date = self > days.times { new_date += ( new_date.wday == 6 ? 3 : 1 ) } > end > end Don't listen to that piece of code. I thought I tested it, but now that I try it, it fails. Here we go: class Date def add_weekdays(days) new_date = self days.times { new_date += ( new_date.wday==5 ? 3 ( new_date.wday==6 ? 2 : 1 ) ) } return new_date end end puts Date.today.add_weekdays(4) #or whatever number Basically, if it's Friday, add 3, if it's Saturday add 2, otherwise add 1. Like I said, though, your loop algorithm should work well. Todd