From: "Jesús Gabriel y Galán" Date: 2010-01-19T19:20:38+09:00 Subject: Re: string to int On Tue, Jan 19, 2010 at 11:13 AM, Phillip Curry wrote: > Is there a nice way to convert a string to an integer if it is in fact an > integer, and to return nil or even an error if it's not?  The method to_i > returns 0 if the string is not an integer, which isn't hugely helpful, as I > want to be able to distinguish between the integer 0 and non-integer > strings. > thanks > Try this: irb(main):002:0> Integer("12") => 12 irb(main):003:0> Integer("fdfdf") ArgumentError: invalid value for Integer: "fdfdf" from (irb):3:in `Integer' from (irb):3 from :0 irb(main):005:0> Integer("12ijk") ArgumentError: invalid value for Integer: "12ijk" from (irb):5:in `Integer' from (irb):5 from :0 irb(main):006:0> "12ijk".to_i => 12 But check the last example: to_i would have returned 12 ignoring the rest of the string, while Integer will raise an exception. Don't know if this fits your criteria. Jesus.