Interesting result of a newbie mistake

Instead of writing
a = %w{ ant cat dog }
I wrote
a = %{ ant cat dog }
puts a[2] --> 110

I didn’t find an explanation for this result in Dave T.’ book
Anybody volunteers a response?

Thanks,
Víctor

2008/5/7 VICTOR GOLDBERG [email protected]:

Instead of writing
a = %w{ ant cat dog }
I wrote
a = %{ ant cat dog }
puts a[2] --> 110

I didn’t find an explanation for this result in Dave T.’ book
Anybody volunteers a response?

irb(main):001:0> a = %{ ant cat dog }
=> " ant cat dog "
irb(main):002:0> a.class
=> String
irb(main):003:0> a[2]
=> 110
irb(main):004:0> a[2].chr
=> “n”

Cheers

robert

When you have somthing like

a = %{ ant cat dog }
=> " ant cat dog "
irb(main):002:0> a.class
=> String
irb(main):003:0> a[2]
=> 110
irb(main):004:0> a[2].chr
=> “n”

it displaying the ascii value of that character at that paticular place

cheers,
kranthi

On Wed, May 7, 2008 at 4:45 PM, Robert K.
[email protected]

On Wed, 2008-05-07 at 20:10 +0900, VICTOR GOLDBERG wrote:

Instead of writing
a = %w{ ant cat dog }
I wrote
a = %{ ant cat dog }
puts a[2] --> 110

I didn’t find an explanation for this result in Dave T.’ book
Anybody volunteers a response?

irb(main):001:0> a = %{ ant cat dog }
=> " ant cat dog "
irb(main):002:0> a[2]
=> 110
irb(main):003:0> a = %w{ ant cat dog }
=> [“ant”, “cat”, “dog”]
irb(main):004:0> a[2]
=> “dog”

They’re different types. The first one came back as the string " ant
cat dog " while the second came back as an array with three strings
[“ant”,“cat”,“dog”]. One of the principles of least surprise in Ruby is
that indexing a string gives you the integer value of the character at
that location. (I may be using a bit of sarcasm with that “principle of
least surprise” thing there…) So a[0] is 32 (the ASCII encoding for
a space), a[1] is 97 (for “a”) and a[2] is 110 (for “n”). If you do it
the right way (for your purposes, I mean) a[0] is “ant”, a[1] is “cat”
and a[2] is “dog”.

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