43

I am looking to turn the character 'a' into 97 in ruby 1.9.2

Ruby 1.8.7

irb(main):001:0> ?a => 97 

Ruby 1.9.2

irb(main):001:0> ?a => "a" 
1

4 Answers 4

69

You probably want String#ord:

% irb ruby-1.9.2-head > 'a'.ord => 97 
Sign up to request clarification or add additional context in comments.

Comments

38

For those, who are looking for the opposite of ord. We have chr

>> "A".ord => 65 >> 65.chr => "A" 

1 Comment

Great - I needed this exactly, to add a gtk-entry that can be toggled by the user, for scrambling/ciphering the alphabet.
3

Note that if you want to write code that is compatible with both Ruby 1.8 and Ruby 1.9, you may want to use String#each_byte like this:

$ irb >> 'a'.each_byte.first => 97 

1 Comment

That is useful to know. I think .ord and .chr are more reliable for the future, though.
-2

?a will return the ASCII value of the char a

2 Comments

Sadly, '?c' will not work same as pre-Ruby 1.9. See eigenclass.org/hiki/Changes+in+Ruby+1.9#l16
?a will return the closest thing to a char type Ruby has, which in Ruby 1.9 is a single-character String and in Ruby pre-1.9 is a Fixnum. String#ord (and its dual Integer#chr) is what you want to use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.