Created
October 3, 2013 02:13
-
-
Save mattcantstop/6803637 to your computer and use it in GitHub Desktop.
A way to drill down and see how much time has expired between two timestamps (integer).
This file contains hidden or 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
module Duration | |
def self.calculate(duration) | |
times = {years: 31536000, months: 2678400, days: 86400, hours: 3600, minutes: 60, seconds: 1} | |
response = '' | |
duration = duration | |
times.each do |time, value| | |
numerator = duration / value if duration >= value | |
duration = duration % value if numerator | |
response << "#{numerator} #{time} " if numerator | |
end | |
puts response | |
end | |
end | |
Duration.calculate(99720045) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great start.
Suggestions:
Your hash syntax is not supported by ruby versions < 1.9. (This matters if you're going to make a gem.)
In math the word numerator has a specific meaning (e.g. the top portion of a fraction) and in this example the word quotient would be better.
What happens in these cases:
calculate(99720045.0)
calculate(nil)
calculate(-1300) # this is a possibility if you subtract the times in the wrong order
When I Google "days in a year" it says 365.242 but you're assuming 365.
I'd change "times.each do |time, value|" to:
time_buckets.each do |time_description, time_in_seconds|
I'd also change the time integers to have an underscore at every 3 numbers e.g. 31536000 => 31_536_000
Correctly pluralizing the words would be good too, like you said.