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:

Copy
>> 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.

Copy
>> 10.seconds.class => ActiveSupport::Duration … >> 1.year.class => ActiveSupport::Duration

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
over 1 year 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