Skip to content

Instantly share code, notes, and snippets.

@mattcantstop
Created October 3, 2013 02:13
Show Gist options
  • Save mattcantstop/6803637 to your computer and use it in GitHub Desktop.
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).
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)
@mattcantstop
Copy link
Author

any recommendations for refactoring are welcome...

@mattcantstop
Copy link
Author

@nick1123 I need to make it so the "s" on each time unit is conditional on if time_unit > 1 but other than that what do you think?

@nick1123
Copy link

nick1123 commented Oct 3, 2013

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.

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