tags:

views:

3318

answers:

6

In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead:

>> a = "0123"
=> "0123"
>> a[0]
=> 48

I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.

+6  A: 

You want a[0,1] instead of a[0].

SCdF
+4  A: 

I believe this is changing in Ruby 1.9 such that "asdf"[2] yields "d" rather than the character code

Stuart
+1  A: 

@Chris,

That's just how [] and [,] are defined for the String class.

Check out the String API.

SCdF
+7  A: 

Or you can convert the integer to its character value:

a[0].chr
Joseph Pecoraro
+1  A: 

The [,] operator returns a string back to you, it is a substring operator, where as the [] operator returns the character which ruby treats as a number when printing it out.

Ben Childs
+2  A: 

To summarize:

This behavior will be going away in version 1.9, in which the character itself is returned, but in previous versions, trying to reference a single character of a string by it's character posision will return its character value (so "ABC"[2] returns 67)

There are a number of methods that return a range of characters from a string (see the Ruby docs on the String slice method) All of the following return "C":

"ABC"[2,1] 
"ABC"[2..2]
"ABC".slice(2,1)

I find the range selector to be the easiest to read. Can anyone speak to whether it is less efficient?

Nathan Fritz