From: Robert Klemme Date: 2010-11-04T18:11:53+09:00 Subject: Re: Ruby Time - Sports Time On Thu, Nov 4, 2010 at 8:50 AM, flebber 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 > user input. > > I am currently planning to use sequel and sqlite to store and query my > data. 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: 1. Use what Time arithmetic provides (Floats) irb(main):011:0> t1=Time.now;sleep 1.2;t2=Time.now;t2 - t1 => 1.205 Then you would have to create a method duration_to_string(d) which creates the string representation that you want, e.g. def duration_to_string(d) min,sec = d.divmod 60 sec,msec = sec.divmod 1 sprintf "%d:%02d:%03d", min, sec, msec * 1000 end 2. 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: http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/