-
-
Save mattcantstop/6803637 to your computer and use it in GitHub Desktop.
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) | |
@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?
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.
any recommendations for refactoring are welcome...