From: Robert Dober Date: 2007-06-22T01:25:34+09:00 Subject: Re: Code Critique: check if int or float On 6/21/07, ole __ wrote: > Thanks Tim and Marcel. > > Would you have thought String.i? and String.f? would make more sense > than Integer() and Float(). They are just not the same, String#i? and String#f? which I would call String#int? and String#float? might be nice for you. You can search the Ruby Change Requests if this was braught up already. It might be a nice thing to have a String#int? without converting actually. >But yeah they will probably make for a > better implementation then the regexps. Hmm not sure at all, let us see 637/137 > cat conversions.rb && ruby conversions.rb # vim: sts=2 sw=2 tw=0 expandtab nu: require 'benchmark' class String def int? /^\d+/ === self end def int1? Integer(self) rescue false end end N=10_000 Benchmark.bmbm do |bench| bench.report( "reg" ) { N.times{ |n| n.to_s.int?; "#{n}x".int? } } bench.report( "Int" ) { N.times{ |n| n.to_s.int1?; "#{n}x".int1? } } end Rehearsal --------------------------------------- reg 0.160000 0.000000 0.160000 ( 0.201496) Int 0.420000 0.000000 0.420000 ( 0.466641) ------------------------------ total: 0.580000sec user system total real reg 0.180000 0.000000 0.180000 ( 0.238369) Int 0.420000 0.010000 0.430000 ( 0.513518) actually the arithmetic part is too costy ;) Cheers Robert --You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw