This is a read-only archive!

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
July 05, 2006 @ 6:07 AM PDT
Cateogory: Programming
Tags: Ruby

4 Comments

Hussam
Quoth Hussam on July 05, 2006 @ 2:53 PM PDT

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'?

Brian
Quoth Brian on July 05, 2006 @ 3:33 PM PDT

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.

Hussam
Quoth Hussam on July 05, 2006 @ 4:17 PM PDT

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.

Hussam
Quoth Hussam on July 09, 2006 @ 5:45 AM PDT

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.