From: Robert Klemme Date: 2004-01-21T19:59:59+09:00 Subject: Re: Parsing periods of time: Code and questions "Josef 'Jupp' SCHUGT" schrieb im Newsbeitrag news:20040120230057.GA3604@jupp%gmx.de... > Hi! > > I am presently working on a new version of my feed aggregator > 'rubric'. This time I am focussing on security issues so among other > changes the config file will no longer be a Ruby script. For parsing > a string that defines a period of time I wrote the following little > routine (GPL applies, long lines but still < 80 characters): > > def to_sec(argument) > return argument if argument.class < Integer > if argument.class == String > case argument > when /^(.*?)[+,](.*)$/ then to_sec($1) + to_sec($2) > when /^\s*([0-9_]+)\s*\*(.+)$/ then $1.to_i * to_sec($2) > when /^\s*[0-9_]+\s*(s(ec(ond)?s?)?)?\s*$/ then argument.to_i > when /^\s*([0-9_]+)\s*m(in(ute)?s?)?\s*$/ then $1.to_i * 60 > when /^\s*([0-9_]+)\s*h(ours?)?\s*$/ then $1.to_i * 3600 > when /^\s*([0-9_]+)\s*d(ays?)?\s*$/ then $1.to_i * 86400 > when /^\s*([0-9_]+)\s*w(eeks?)?\s*$/ then $1.to_i * 604800 > when /^\s*([0-9_]+)\s*months?\s*$/ then $1.to_i * 2419200 > else 0 > end > end > end > > Two questions arise: > > 1. Should one require integral values or would it be better to allow > the use of decimal numbers? Seems better to me. Seconds may in fact be fractional values. > 2. If decimal numbers are allowed would it be a good idea to allow > the use of exponential notation? Why not? The standard conversion does it anyway. But maybe I'd change the code above to reduce the number of regexps. Maybe something along these lines: def to_sec(argument) return argument if argument.class < Integer if argument.class == String tokens = argument.scan /[*+/-] |[+-]?\d+(\.\d+)?([eE][+-]?\d+)? |\w+ /x # process tokens end end Well, a full blown version would use it's own parser... Regards robert