Jeremy Jeremy - 4 months ago 33
Ruby Question

How to efficiently convert minutes to "hours:minutes"

For a tutorial I need to write a method that will take in a number of minutes, and return a string that formats the number into "hours:minutes".

My answer was:

def time_conversion(minutes)
hrs = 0
min = 0
if minutes >= 60
min = minutes % 60
hrs = (minutes - min) / 60
min = format('%02d',min)
min = minutes
return "#{hrs}:#{min}"

The tutorial answer is:

def time_conversion(minutes)
hours = 0

while minutes >= 60
hours += 1
minutes -= 60

if minutes < 10
minutes_s = "0" + minutes.to_s
minutes_s = minutes.to_s

return hours.to_s + ":" + minutes_s

They both seem to return the same thing. Is my answer OK, or is theirs a better solution?


Your answer is perfectly fine, if not a better more succinct way for making the method. Performance wise, your answer is only minimally better as you're using a modulos operation where they are using a while loop in their code. I believe the tutorial is answered the way it is, is so that beginners can better grasp control flow and loops. Lastly, you can leave out the 'return' on the second to last line as ruby will implicitly return the last thing it evaluates in a method. But that's more of a individual preference just incase you come across it.