Posted over 6 years ago. Visible to the public.

Heads up! Years are always floats in Rails < 4

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.

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 (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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Arne Hartherz
Last edit:
almost 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more