From: Robert Klemme Date: 2007-10-26T07:00:17+09:00 Subject: Re: Change a string to an integer, report an error if the string does not represent an integer? On 25.10.2007 18:54, Stefano Crocco wrote: > Alle giovedì 25 ottobre 2007, Randy Kramer ha scritto: >> Can anybody point me to a way to check if a string represents a valid >> integer and then convert it to an integer? >> >> It is very likely the string will contain leading zeros, and should not >> contain any trailing non-numeric characters. >> >> Per the documentation (pickaxe 2), to_i won't quite do it, it will just >> ignore trailing non-numeric characters. >> >> Thanks! >> >> Randy Kramer > > Kernel.Integer can convert a string to a number raising an exception if it has > the wrong format. The only problem lies in the fact that it treats a string > with leading zeros as an octal number (for example, Integer("000123") gives > 83). To avoid this, you can use gsub on the string: > > Integer("000123".gsub(/^0+/,'')) > => 123 > > I hope this helps I'd rather do Integer(s.sub(/\A([+-]?)0+(?=.)/, '\\1')) because your regexp has some issues: 1. "+010" is unchanged and will yield 8 instead of 10 2. same for negative numbers 3. "00" will be converted to "" which will trigger an error 4. you use gsub although the regular expression can match only once Subtle, subtle... Kind regards robert