Interesting result of a newbie mistake

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+Ruby+1.9#l116\).

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/ProgrammingRuby/
you will find examples showing this behavior.

Christophe

···

----- Original Message ----

Thanks,
Víctor

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+Ruby+1.9#l116\).

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/ProgrammingRuby/
you will find examples showing this behavior.

Christophe

Thanks,
Víctor