On Thu, Nov 4, 2010 at 8:50 AM, flebber [email protected] wrote:
Hi I am reading the time classes for Ruby. However I can’t figure out
what time method would be best for sports times. I am referring to
this link http://www.ruby.ch/ProgrammingRuby/htmlC/ref_c_time.html
I want the times stored to be in a mm:ss:hh format or ss:hh (where hh
= hundreths of seconds).
First we should distinguish between storage and representation. You
may want to print (i.e. use a representation) times in the format you
give but that does not necessarily mean that you also want or need to
store them that way.
The times stored will be of times occuring over distance, and some
will be imported from internet sources and some will come from direct
I am currently planning to use sequel and sqlite to store and query my
Second, it seems you want to store durations not points in time,
which is what class Time is for. For storing durations and doing the
kind of math with them that you indicate it’s best to base it on some
numeric type, see below.
Any suggestions on the best and most reliable format? I forgot to
mention that sums and calculations including averages will be
performed on the times.
I see two reasonable approaches:
- Use what Time arithmetic provides (Floats)
irb(main):011:0> t1=Time.now;sleep 1.2;t2=Time.now;t2 - t1
Then you would have to create a method duration_to_string(d) which
creates the string representation that you want, e.g.
min,sec = d.divmod 60
sec,msec = sec.divmod 1
sprintf “%d:%02d:%03d”, min, sec, msec * 1000
- Create a custom class Duration that contains a Float for the
duration, implements all the math operators and which implemens #to_s
with the code of duration_to_string above.
Downside of this approach is that you then normally would want to
change Time#+, Time#- etc. to return an instance of Duration and not
Float to have it all nicely integrated. With some effort you can get
that done and probably also keep most code compatible. That would be
a nice experiment.
You can find more info on approach 2 here: