I’m sure you’ve probably seen this question in your programming classes.. I decided I wanted to play with Ruby again and was remind of this problem, so thought it might be fun as a simple exercise to do this in Ruby.
The problem is to take a long integer and convert it to hours, minutes and seconds. This is a common issue in games, for example, where a countdown timer is represent internally in seconds. But players don’t want to see some huge number like 43678 seconds. They’d rather see 12:07:58 for hours, minutes and seconds. A couple of uses of the mod operator, and a couple of uses of the built-in formatter and you’re good to go.
Update: I wanted to clean up the code a bit more and put the ruby equivalent of a “main” via the __FILE__ check. This way you can just reuse the code via require if you so desire.
#!/usr/bin/env ruby class TimeFormatter def format_time (timeElapsed) @timeElapsed = timeElapsed #find the seconds seconds = @timeElapsed % 60 #find the minutes minutes = (@timeElapsed / 60) % 60 #find the hours hours = (@timeElapsed/3600) #format the time return hours.to_s + ":" + format("%02d",minutes.to_s) + ":" + format("%02d",seconds.to_s) end end if __FILE__ == $0 formatter = TimeFormatter.new puts formatter.format_time(43678) end
Categories:
Tags:
