Re: Interesting result of a newbie mistake

----- Original Message ----

From: VICTOR GOLDBERG [email protected]
To: ruby-talk ML [email protected]
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 T.’ 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

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

Víctor

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

[email protected] wrote in message
news:[email protected]

----- Original Message ----

From: VICTOR GOLDBERG [email protected]
To: ruby-talk ML [email protected]
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 T.’ 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs