From: ara.t.howard@... Date: 2006-08-25T07:36:57+09:00 Subject: Re: Alternative to String#to_i ? On Fri, 25 Aug 2006, Jeremy Lizt wrote: > Thanks to everyone for the quick response. The Integer suggestion works > great, but I'll point out one wrinkle that I encountered: > > Integer nil # => 0 > > That was a small surprise. (These zeros keep popping up when you may > not expect them!) My little conversion method now works fine and looks > like this: > > def string_to_i(str) > if str.nil? then return nil else Integer str end > rescue nil > end fyi. harp:~ > irb irb(main):001:0> Integer '08' ArgumentError: invalid value for Integer: "08" from (irb):1:in `Integer' from (irb):1 i use this # # convert a string to an integer of any base # def strtod s, opts = {} base = opts['base'] || opts[:base] || 10 case base when 2 s = "0b#{ s }" unless s =~ %r/^0b\d/ when 8 s = "0#{ s }" unless s =~ %r/^0\d/ when 16 s = "0x#{ s }" unless s =~ %r/^0x\d/ end Integer s end # # convert a string to an integer base 10 # def atoi s strtod "#{ s }".gsub(%r/^0+/,''), :base => 10 end -a -- to foster inner awareness, introspection, and reasoning is more efficient than meditation and prayer. - h.h. the 14th dalai lama