user1843757
user1843757

Reputation: 33

Getting ASCII value of ith character instead of character in Ruby

I'm a beginner with Ruby and I'm trying to get a certain character in a string in Ruby like so:

string1 = "ohhideraaaa"
puts string1[0]

and it's returning 111 rather than "o". I'm sure I'm doing something really stupid, does anyone have any idea what it is?

Upvotes: 2

Views: 183

Answers (2)

ruakh
ruakh

Reputation: 183321

I think the best fix is to upgrade to Ruby 1.9.3, the current stable release; you are apparently using 1.8.x, where an expression like yours returns the code of the character at that position, but in 1.9.x, it returns a substring of one character at that position, which is what you want.

If upgrading is not an option, or if you would prefer to stick with Ruby 1.8.x, you can persuade it to give you a substring rather than a character-code by specifying a length as well (in your case, 1):

puts string1[0,1]

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993163

Use .chr:

puts string1[0].chr

The .chr method converts an ASCII integer value back to a character.

Upvotes: 0

Related Questions