Skip to content

Instantly share code, notes, and snippets.

@chubas
Created October 26, 2010 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chubas/646101 to your computer and use it in GitHub Desktop.
Save chubas/646101 to your computer and use it in GitHub Desktop.
WTF arithmetics
t = Time.now
wtf = 2.years
puts wtf.to_i #=> 63115200
puts ((t + wtf) - t).to_i #=> 63158400
@hectorsq
Copy link

It seems that the problem is that wtf is float and the arithmetic is done in floating point.

Forcing wtf to integer yields the right result

puts wtf.class # => Float

puts t + wtf.to_i - t #=> 63115200.0

Surprise! The last result is Float too! It seems that the principle of least surprise is not followed here!

@chubas
Copy link
Author

chubas commented Oct 26, 2010

Not really. I found that time arithmetics take into account the leap years, the daylight saving zones and other time anomalies.
2.years returns a Duration object (http://github.com/rails/rails/blob/master/activesupport/lib/active_support/duration.rb) mimicking a float:

year = ActiveSupport::Duration.new(365.25.days, [[:years, 1]])
year.class  #=> Float. Surprise!

so t + 2.years is actually different than t + 2.years.to_f, some coercion magic is happening there.

Lesson learned: You think you know how to count time. Think twice =S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment