From: 7stud -- Date: 2007-10-26T02:52:18+09:00 Subject: Re: Change a string to an integer, report an error if the string does not represent an integer? Randy Kramer wrote: > 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 >Integers can also be negative. Integers can also have leading '+' signs. :) Another way: def valid_int?(str) start = true str.each_byte do |char| if start start = false if char == ?+ or char == ?- next end end if char < ?0 or char > ?9 return false end end return true end strings = ['0013abc', '0025', '-0030', '+051', '00-1', '-abc72'] strings.each do |str| if valid_int?(str) puts str.to_i else puts 'invalid int' end end -- Posted via http://www.ruby-forum.com/.