From: Phillip Curry Date: 2010-01-19T19:26:06+09:00 Subject: Re: string to int --000e0cd1ab44b1aa85047d81e5bd Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Yeah that's exactly what I was looking for. Thanks for the help, I'm prett= y new to ruby and still exploring all this stuff. 2010/1/19 Jes=FAs Gabriel y Gal=E1n > 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") > =3D> 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 > =3D> 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. > > --000e0cd1ab44b1aa85047d81e5bd--