[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Interesting result of a newbie mistake

maestroiut-rubytalk

5/7/2008 1:46:00 PM

=0A=0A----- Original Message ----=0A> From: VICTOR GOLDBERG <vmgoldberg@ver=
izon.net>=0A> To: ruby-talk ML <ruby-talk@ruby-lang.org>=0A> Sent: Wednesda=
y, May 7, 2008 1:10:17 PM=0A> Subject: Interesting result of a newbie mista=
ke=0A> =0A> Instead of writing=0A> a =3D %w{ ant cat dog }=0A> I wrote=0A> =
a =3D %{ ant cat dog }=0A=0AThat defines a string. =0A=0A> puts a[2] =
--> 110=0A=0AThe reason is that indexing a string in Ruby 1.8 and p=
revious versions returns the character code.=0AThat usually comes as a surp=
rise to beginners. This behavior changes in Ruby 1.9 to return the characte=
r (see http://eigenclass.org/hiki.rb?Changes+in+Rub...).=0A=0ASee th=
e following IRB Ruby 1.8 session:=0A=0A$ irb=0A>> a =3D %{ ant cat dog }=0A=
=3D> " ant cat dog "=0A>> a.class=0Aa.class=0A=3D> String=0A>> a[2]=0Aa[2]=
=0A=3D> 110=0A>> a[2].chr=0Aa[2].chr=0A=3D> "n"=0A>> =0A> =0A> I didn't fin=
d an explanation for this result in Dave Thomas' book=0A> Anybody volunteer=
s a response?=0A=0AIf you look for the String class and the chr method into=
the index of the first edition =0Ahttp://ruby-doc.org/docs/Progra...
/=0Ayou will find examples showing this behavior.=0A=0AChristophe=0A=0A> =
=0A> Thanks,=0A> V=EDctor=0A

1 Answer

VICTOR GOLDBERG

5/7/2008 2:30:00 PM

0

Thank you all that responded.
maestroiut's explanation was especially enlightening.

Víctor

================================================

<maestroiut-rubytalk@yahoo.com> wrote in message
news:112782.26330.qm@web54305.mail.re2.yahoo.com...


----- Original Message ----
> From: VICTOR GOLDBERG <vmgoldberg@verizon.net>
> To: ruby-talk ML <ruby-talk@ruby-lang.org>
> Sent: Wednesday, May 7, 2008 1:10:17 PM
> Subject: Interesting result of a newbie mistake
>
> Instead of writing
> a = %w{ ant cat dog }
> I wrote
> a = %{ ant cat dog }

That defines a string.

> puts a[2] --> 110

The reason is that indexing a string in Ruby 1.8 and previous versions
returns the character code.
That usually comes as a surprise to beginners. This behavior changes in Ruby
1.9 to return the character (see
http://eigenclass.org/hiki.rb?Changes+in+Rub...).

See the following IRB Ruby 1.8 session:

$ irb
>> a = %{ ant cat dog }
=> " ant cat dog "
>> a.class
a.class
=> String
>> a[2]
a[2]
=> 110
>> a[2].chr
a[2].chr
=> "n"
>>
>
> I didn't find an explanation for this result in Dave Thomas' book
> Anybody volunteers a response?

If you look for the String class and the chr method into the index of the
first edition
http://ruby-doc.org/docs/Progra...
you will find examples showing this behavior.

Christophe

>
> Thanks,
> Víctor