Longest ten weeks ever

By squarewheel

This is not really about Rails, more about Ruby itself. Look at this snippet of code:

print Date.today + 10.weeks

The intention of the programmer is quite obvious. The result – not so much:

18566-09-12

Rationale behind this result is quite simple – 10.weeks returns 6048000 – plain Fixnum being 10 weeks in seconds. So the correct code should be:

print (Time.now + 10.weeks).to_date.to_s

Obvious, isn’t it?

3 Responses to “Longest ten weeks ever”

  1. squarewheel Says:

    This got fixed in Rails 2

  2. apohllo Says:

    Actually it is not RUBY bug or misdesign – methods such as week(s) on fixnums are provided by RAILS core extensions.

  3. squarewheel Says:

    Yes, right. Besides – it got somewhat better in rails 2, but still causes problems. A real TimeSpan type would be better than bare ints, but introducing this now would cause lots of compatibility problems. Perhaps this need to wait for rails 3.

Leave a Reply