From: Christophe Broult Date: 2002-01-22T07:17:11+09:00 Subject: RE: converting chars to numeric This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C1A2C7.0EE0A700 Content-Type: text/plain > -----Original Message----- > From: Mark Probert [mailto:probertm@nortelnetworks.com] [...] > > Hi. > > I am new to ruby and coming from a Perl environment. There are no automatic type conversion in Ruby. The Ruby Way has a section for Perl programmers. This is an excellent book. > > Can someone tell me if there is a nice way to do the following: > > s = "4567" > a = s[0] # --> I want the value '4' > not '54', the > ASCII value of 4 > b = s[1] # --> 5 > a + b # --> 9 > > I can do this by saying > > a = s[0] - 48 a = s[0..0].to_i will do what you want since it extracts the substring containing the first character of the string and you then convert that string to an integer. s[0] gives you the first character of the string and IIRC (as it is said in the Ruby Way) characters in Ruby are integers which explains why you get the code ASCII of '4'. Christophe ------_=_NextPart_001_01C1A2C7.0EE0A700 Content-Type: text/html Content-Transfer-Encoding: quoted-printable RE: converting chars to numeric

> -----Original Message-----
> From: Mark Probert [mailto:probertm@nortelnetwor= ks.com]

[...]

>
> Hi.
>
> I am new to ruby and coming from a Perl = environment.

There are no automatic type conversion in Ruby. The = Ruby Way has a section for Perl programmers. This is an excellent = book.

>
> Can someone tell me if there is a nice way to = do the following:
>
>          s = =3D "4567"
>          a = =3D = s[0]           &n= bsp;    # --> I want the value '4'
> not '54', the
> ASCII value of 4
>          b = =3D = s[1]           &n= bsp;    # --> 5
>          a + = b            = ;       # --> 9
>
> I can do this by saying
>
>          a = =3D s[0] - 48

 a =3D s[0..0].to_i

will do what you want since it extracts the substring = containing the first character of the string and you then convert that = string to an integer.

s[0] gives you the first character of the string and = IIRC (as it is said in the Ruby Way) characters in Ruby are integers = which explains why you get the code ASCII of '4'.

Christophe

------_=_NextPart_001_01C1A2C7.0EE0A700--