Jeremy Jeremy - 11 days ago 6
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)
else
min = minutes
end
return "#{hrs}:#{min}"
end


The tutorial answer is:

def time_conversion(minutes)
hours = 0

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

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

return hours.to_s + ":" + minutes_s
end


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

Answer

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.

Comments