String Element Reference

I am new to Ruby so I apologize if this seems dumb.

I am currently running ruby 1.8.7 (2009-06-12 patchlevel 174)
[universal-darwin10.0].

When working in an irb session I’m having trouble with String element
reference.

Example:

a = “hello”

a[0] should return “h”, but instead is returning 104.

Seems like it’s return the ascii value of the element, but why?

When I do a[0,3] the return is the expected “hel”.

Any ideas as to why a[0] is returning a FixNumb object?

Ideas / help would be greatly appreciated.

On 25.05.2011 19:23, jason solomon wrote:

a = “hello”

Any ideas as to why a[0] is returning a FixNumb object?

Ideas / help would be greatly appreciated.

This has changed in Ruby 1.9. You probably read 1.9 documentation
that’s why you expect a[0] to return “h”.

Kind regards

robert

Thanks, appreciate the help.

jason solomon wrote in post #1000974:

Any ideas as to why a[0] is returning a FixNumb object?

For some reason Matz thought it was more useful to define the [] method
for the String class to return the ascii value of the character. As you
discovered, if you specify a length as the second argument, you get the
actual characters. Applying that knowledge, if you specify a length of
1, you will get a single character. So the expression:

str[0,1]

will return a character in both ruby 1.8 and ruby 1.9.

If I were you, I would upgrade to ruby 1.9.2(or whatever the
latest version is), and learn the latest version.

That is the way String indexing works in Ruby, if you only pass one
parameter you’ll get the ASCII value of the character. If you would like
to get “h” you must do a[0,1] where the first parameter tells the
parser to get the first character of the String and the second parameter
tells the number of characters you want to get from that position.
Hope this helps
Javier Hidalgo