Created
October 26, 2010 00:43
-
-
Save chubas/646101 to your computer and use it in GitHub Desktop.
WTF arithmetics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t = Time.now | |
wtf = 2.years | |
puts wtf.to_i #=> 63115200 | |
puts ((t + wtf) - t).to_i #=> 63158400 |
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
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!