35

How do I obtain the ASCII value of a character in Ruby 1.9?

I searched the Internet far and wide, but without success. I tried ?x and "x"[0], but all they return is "x".

LakatosI
  • 395
  • 1
  • 3
  • 9
  • possible duplicate of [Getting an ascii character code in ruby - ? fails](http://stackoverflow.com/questions/1270209/getting-an-ascii-character-code-in-ruby-fails) – Jörg W Mittag Mar 03 '11 at 12:06
  • 4
    "I searched the Internet far and wide, but without success.". Hmm. The [search engines](http://www.google.com/search?q=ruby+1.9+character+ordinal+value) must have had a bad day. – the Tin Man Mar 03 '11 at 15:47
  • 3
    @the Tin Man: Maybe the OP didn't know the word "ordinal". – Andrew Grimm Mar 03 '11 at 22:30
  • 1
    @Andrew Grimm - sigh... now I know my place in life. I find things for others. – the Tin Man Mar 04 '11 at 02:16

4 Answers4

57

The String#ord method will do the trick:

ruby-1.9.2-p136 > 'x'.ord
 => 120 
ruby-1.9.2-p136 > '0'.ord
 => 48 
ruby-1.9.2-p136 > ' '.ord
 => 32 
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
16

You can also use

ruby-2.0.0p353 > "x".sum
=> 120

ruby-2.0.0p353 > "a string".sum
=> 792 

The 'sum' method will find the sum of all character codes, but if you put only one character it will give you the code of that one only.

Sh.K
  • 289
  • 3
  • 4
6
x.ord

http://www.ruby-doc.org/core/classes/String.html#M001177

randomguy
  • 12,042
  • 16
  • 71
  • 101
0

I was also stuck with this, ord only works from string to number and not vice versa. The solution is:

def getChar(a):
 return a.chr
end
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
lare
  • 1