Ruby date enumeration
The Date class in ruby provides an upto method, so you can iterate over a series of dates.
Date.new(2000,1,1).upto( Date.new(2001,1,1) ) do |d|
puts d
end
This counts by days, so it will print 365 values or so from 2000-01-01 to 2001-01-01.
What if you want to count by months? Being able to modify classes in Ruby makes this easy enough. Not sure this handles all situations, but it worked for what I needed.
class Date
def +(n)
if n == 0 then
return self
elsif self.month + n > 12
return Date.new(
self.year + (n.to_f / 12).ceil,
(self.month + n) % 12,
self.day
)
else
return Date.new(self.year, self.month + n, self.day)
end
end
def upto(max)
date = self
until date > max do
yield date
date = date + 1
end
end
end
Date.new(2000,1,1).upto( Date.new(2001,1,1) ) do |d|
puts d
end
4 Comments
In other news I'm back to Ubuntu.
And now that I have wiped my .mozilla directory, what's a good browsing font? Something that is capable of 'bold' and views fairly well at tiny font sizes.
I have just started programming. Isn't what you did called 'overloading'?
Bitstream Vera is good for browsing.
The + operator was already overloaded by default for the Date class in a standard Ruby library. All I did was redefine the + method. So I sort of re-overloaded it.
Ah, thank you for the explanation.
I'm browsing with Bitstream Vera right now. Looks promising!
First place I hit was Gentoo Forums: Off the wall. Now I hope I don't regret posting this here but I'm literally in tears over this.
Link
NSFW by the way.
Well I thought since I'm already spamming your website there's no harm in posting one more. But this time I won't post a link.
Please go through the trouble of looking for a video called "Pythagoras switch". I'm sure you will be ammused.
Speak your Mind
Preview