Read more

Heads up! Years are always floats in Rails < 4

Arne Hartherz
March 06, 2013Software engineer at makandra GmbH

Watch out when saying something like 1.year in Rails. The result is not a Fixnum and can cause unexpected errors when the receiving end expects a Fixnum.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

While anything from seconds to months are Fixnums, a year is a Float in Rails -- when called on a Fixnum itself:

>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.

While they are technically correct Show archive.org snapshot (a year is almost never exactly 365 days), even 1.year.to_f won't return a result that would justify always using floats: 31557600.0 is just the same as 365.days.to_f.

Note that saying something like 8.5.hours will be a Float (for somewhat obvious reasons).

Rails 4

Introduced by Rails 4 accurate date and time measurements are provided by ActiveSupport::Duration. It mainly supports the methods on Numeric.

>> 10.seconds.class
=> ActiveSupport::Duration
…
>> 1.year.class
=> ActiveSupport::Duration
Posted by Arne Hartherz to makandra dev (2013-03-06 10:52)